I need to clear a basic concept. This code works fine. Can somebody explain me that if the function calDouble already returning the address (reference) of int why I need to use & operator further in main int *j = &calDouble(i); to get the address (reference) of int? Thanks.
int& calDouble(int x)
{
x = x*2;
return x;
}
int main(int argc, char *argv[])
{
int i = 99;
int *j = &calDouble(i);
system("PAUSE");
return EXIT_SUCCESS;
}
int& calDouble(int x)doesn’t return an address, but a reference to anint.You need to take the address of the reference to be able to assign it to a pointer.
Note however that your code invokes undefined behavior. Because you pass the parameter by value, a copy of it is created inside the function. So you return a local variable by reference, which is not legal.
I think your confusion comes from
&. This can be used in two ways:&x, it takes its addressint& x, it defines a referenceA reference is just an alias, a different name for a variable.
Now,
xandyrefer to the same variable.takes the address of
x.