I have this function that swaps integers passed by reference, it works fine in C++ but it does not work in C.
#include <stdio.h>
void swap(int & x, int & y)
{
int z = x;
x = y;
y = z;
}
int main()
{
int a = 0, b = 1;
swap(a, b);
printf("a is now %d\n", a);
printf("b is now %d\n", b);
}
Why doesn't it work in C?
C and C++ have some overlap, but they are two different languages. C has no references.
Even the claim that C++ is a superset of C is outdated. C has evolved since C++ started as "C with classes" and not all features added to C are also incorporated into C++. Hence it should not be too surprising that what works in one does not necessarily work in the other.
These are two different languages, you can't expect that something that works in one can work in the other, passing by reference is not possible in C.
You can, however, pass by pointer:
#include <stdio.h>
void swap(int* const x, int* const y)
{
int z = *x;
*x = *y;
*y = z;
}
int main()
{
int a = 0, b = 1;
swap(&a, &b);
printf("a is now %d\n", a);
printf("b is now %d\n", b);
}
This line declares 2 parameters as references:
void swap(int & x, int & y)
The C language does not have references.
If you attempt to compile this with a C compiler, you should get:
error: expected ‘;’, ‘,’ or ‘)’ before ‘&’ token
IDEOne link
C does not have references but you can use pointers or make a macro:
#include <stdio.h>
#define swap(X,Y) do {int Z=X; X=Y; Y=Z;} while(0)
int main()
{
int a = 0, b = 1;
swap(a, b);
printf("a is now %d\n", a);
printf("b is now %d\n", b);
}
AS in c language to be able to change the actual value for a certain variable you should call it by reference so in this code to be able to change (swape) between variables you should use method of call by address ( here when you finish swape function the copied variables will be removed from the memory and actual variables will stay with the same values )
#include <stdio.h>
void swap(int* x, int* y)
{
*x=*x^ *y;
*y=*x ^ *y;
*x=*x ^ *y;
}
int main()
{
int a =0, b = 1;
swap(&a,&b);
printf("a is now %d\n", a);
printf("b is now %d\n", b);
}
note: swap(a,b); is wrong in c language you should pass these variables by address to be able to swape their values as swape function return void
another solution
#include <stdio.h>
void swap(int* x, int* y)
{ int z = *x ;
*x = *y ;
*y=z;
}
int main()
{
int a = 0, b = 1;
swap(&a, &b);
printf("a is now %d\n", a);
printf("b is now %d\n", b);
}
Related
I am practicing functions in C++. In some random notes, I found an example of functions call by value and call by reference.
The code is
#include <string.h>
#include <iostream>
#include<stdio.h>
using namespace std;
void F1(float a, float b)
{
a++;b++;
}
void F2 (float &a, float &b)
{
a++;
b++;
}
int main ()
{
float a=9,b=5;
float *ptrA=&a;
float *ptrB=&b;
F1(a,b);
cout<<"\na:"<<a<<"\nb:"<<b;
F2(a,b);
cout<<"\na:"<<a<<"\nb:"<<b;
}
Now for the function F2, I am confused that in the main function I have passed the value of a and b and in the definition it received the address of the variable a and b. Then how will the increment be done in the values of a and b?
The call
F2(a,b);
Actually sends the addresses of a and b, and not their values, because of the way F2 is declared. In C++, references are like pointers, just with a cleaner syntax. So F2 actually gets the addresses of a and b, and then a++ and b++ operate on the original variables defined in main().
It looks like you're after passing a float pointer to the function
void F1(float a, float b)
{
a++;b++;
}
void F2 (float* a, float* b)
{
a++;
b++;
}
int main()
{
float a, b;
a = 5;
b = 7;
F1(a, b);
// a is still 5 and b 7
F2(&a, &b);
// a is 6 b is 8
}
I am using function overload to have a general version of a behaviour and a more usual one. The usual function just picks a default value for the second argument that actually depends on the first, and the compiler is giving me an error because it does not even recognize the existence of the second function. I also tried to do it with default values, but because the default depends on the first argument, the compiler does not seem to accept it.
So, here are simplified examples just for illustration.
Function overloading case:
#include <stdio.h>
struct pair {
int x;
int y;
};
int func(pair a){
return func(a, a.y);
}
int func(pair a, int b) {
return a.x*b;
}
int main() {
pair z;
z.x = 2;
z.y = 4;
printf("%d\n", func(z));
printf("%d\n", func(z,12));
}
This gives me the error:
a.c: In function ‘int func(pair)’:
a.c:9:21: error: too many arguments to function ‘int func(pair)’
a.c:8:5: note: declared here"
Example with default values:
#include <stdio.h>
struct pair {
int x;
int y;
};
int func(pair a, int b = a.y) {
return a.x*b;
}
int main() {
pair z;
z.x = 2;
z.y = 4;
printf("%d\n", func(z));
printf("%d\n", func(z,12));
}
Gives me the following error: "local variable a may not appear in this context"
So, is there any way in C++ to emulate this behaviour? I never had this problem in other languages, like Java or even in ASP.
Thank you all.
In C and C++, before the function call, that function should be declared or defined. Here you are making a call to return func(a, a.y); but the function func(pair, int) has not yet been declared or defined.
You need to change the definitions of the two functions, or just declare the functions in the beginning of your code. As other answers have explained the first approach, here is the snippet with second approach.
#include <stdio.h>
//Function Declaration
int func(pair);
int func(pair, int);
struct pair {
int x;
int y;
};
int func(pair a){
return func(a, a.y);
}
int func(pair a, int b) {
return a.x*b;
}
int main() {
pair z;
z.x = 2;
z.y = 4;
printf("%d\n", func(z));
printf("%d\n", func(z,12));
}
Switch the order of the definitions of func(), such that the 2 argument version is defined before the one argument version. The compiler doesn't know the 2 argument version exists until it encounters the definition, so you can't call it until you've told the compiler it exists.
You have to change the order of the definitions:
int func(pair a, int b) {
return a.x*b;
}
int func(pair a){
return func(a, a.y);
}
LIVE DEMO
This is happening because in int func(pair a) you are calling int func(pair a, int b) which is not visible. Changing the order of definitions like above solves this problem.
struct { int a, b; } f(int x, int y) // OK
{
return { x, y };
}
auto g(int x, int y) -> struct { int a, b; } // error C2332
{
return { x, y };
}
int main()
{
auto n = f(1, 2).a; // OK
}
My compiler is VC++ 2013 RC.
Why is g wrong while f is OK?
Is this a bug of VC++?
Actually, in C++, it's illegal to define a type in a parameter or return type, named or not. See C++11[diff.decl]:
Change: In C++, types may not be defined in return or parameter types. In C, these type definitions are allowed
So the actual problem is the first case being accepted, not the second one being rejected.
I just wanted to clarify something, imagine we have the function signature:
1) int* X(){}
2) int Y(){}
3) int& Z(){}
I am trying to work out the exhaustive possibilities of types of values I can return for the above. The below show possible implementations for the above function bodies:
1)
int* X(){
int* b = new int(6);
return b;
}
2)
int Y(){
int b = 6;
return b;
}
or
int Y(){
int* b = new int(6);
return *b;
}
EDIT: 2) not good because of memory leak if b isn't deleted.
3)
int& Z(){
int b = 6;
return b;
}
EDIT: 3) not good because b will go out of scope once function returns.
Is there anything I have missed out which could be returned from any of the above 3 function signatures? Getting a bit more adventurous, what about:
int* X(){
int b = 6;
return reinterpret_cast<b>;
}
and
int X(){
int* b = new int(6);
return reinterpret_cast<b>;
}
? (My understanding of reinterpret_cast may be wrong...)
int Y(){
int* b = new int(6);
return b*;
}
This has a syntax error. To dereference b, you would do *b. Nonetheless, this is a very bad implementation because it leaks memory. The dynamically allocated int will never be destroyed.
int& Z(){
int b = 6;
return b;
}
This is also bad because you are returning a reference to a local variable. The local variable b will be destroyed when the function returns and you'll be left with a reference to a non-existent object.
int* X(){}
when you have to return address which is pointing to integer
int Y(){}
for returning simple integer
int& Z(){}
this is something different,
you don't have any argument in Z() thus it is useless.
It must be like
int& Z(int &a)
{
//code body
return (a);
}
and return this to reference variable
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How does dereferencing of a function pointer happen?
Hi All,
Why these two codes give the same output,
Case 1:
#include <stdio.h>
typedef void (*mycall) (int a ,int b);
void addme(int a,int b);
void mulme(int a,int b);
void subme(int a,int b);
main()
{
mycall x[10];
x[0] = &addme;
x[1] = &subme;
x[2] = &mulme;
(x[0])(5,2);
(x[1])(5,2);
(x[2])(5,2);
}
void addme(int a, int b) {
printf("the value is %d\n",(a+b));
}
void mulme(int a, int b) {
printf("the value is %d\n",(a*b));
}
void subme(int a, int b) {
printf("the value is %d\n",(a-b));
}
Output:
the value is 7
the value is 3
the value is 10
Case 2 :
#include <stdio.h>
typedef void (*mycall) (int a ,int b);
void addme(int a,int b);
void mulme(int a,int b);
void subme(int a,int b);
main()
{
mycall x[10];
x[0] = &addme;
x[1] = &subme;
x[2] = &mulme;
(*x[0])(5,2);
(*x[1])(5,2);
(*x[2])(5,2);
}
void addme(int a, int b) {
printf("the value is %d\n",(a+b));
}
void mulme(int a, int b) {
printf("the value is %d\n",(a*b));
}
void subme(int a, int b) {
printf("the value is %d\n",(a-b));
}
Output:
the value is 7
the value is 3
the value is 10
I'll simplify your question to show what I think you want to know.
Given
typedef void (*mycall)(int a, int b);
mycall f = somefunc;
you want to know why
(*f)(5, 2);
and
f(5.2);
do the same thing. The answer is that a function name both represent a "function designator". From the standard:
"A function designator is an expression that has function type. Except when it is the
operand of the sizeof operator or the unary & operator, a function designator with
type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to
function returning type’’."
When you use the indirection operator * on a function pointer, that dereference is also a "function designator". From the standard:
"The unary * operator denotes indirection. If the operand points to a function, the result is
a function designator;..."
So f(5,2) becomes essentially (*f)(5,2) by the first rule. This becomes call to function designated by f with parms (5,2) by the second. The result is that f(5,2) and (*f)(5,2) do the same thing.
Because function pointers are automatically resolved whether you use them with or without the dereference operator.
you don't have to use & before function name
x[0] = addme;
x[1] = subme;
x[2] = mulme;
however both ways are valid.