Assume that c and d are simple integers.
Why does the code written above work perfectly? Even though c isn't a reference variable, the function returnC() returns the integer without problems. Why does this happen? Thanks for any answers!
I'm not expecting them to fail. I don't understand the reason why they work.
A function with a type of int&should return reference variables. But in this case it is also returning simple integer variables. I don't understand why this happens.
> A function with a type of int& should return reference variables.
> But in this case it is also returning simple integer variables.
It is returning a reference to int.
The semantics of return involves the semantics of initialization.
1 2 3 4 5 6 7 8 9 10 11
double foo()
{
int i = 1234 ;
return i+3 ; // return a double initialized with the expression i+3
}
int& bar()
{
staticint i = 1234 ;
return i ; // return a reference to int, initialized to refer to i
}
int& bar()
{
staticint i = 1234 ;
return i ; // return a reference to int, initialized to refer to i
}
The comment says that initialized to refer to i
How and why does this happen? Also, I didn't understand what you mean when you wrote The semantics of return involves the semantics of initialization. I request you to elaborate your explanation. Thanks!
if not so, maybe one more hint>
do not read reference variable as in
c isn't a reference variable
read reference to a variable instead:
So int & returnC() is expected to return a reference to a variable, which is exactly what it does with return c and which is exactly what it cannot do with return 153;