Is the following code (func1()) correct if it has to return i? I remember reading somewhere that there is a problem when returning reference to a local variable. How is it d
A good thing to remember are these simple rules, and they apply to both parameters and return types...
There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int*
and returning &i
would have been equally incorrect. You would be better off in that case doing this...
void func1(int& oValue)
{
oValue = 1;
}
Doing so would directly change the value of your passed in parameter. Whereas this code...
void func1(int oValue)
{
oValue = 1;
}
would not. It would just change the value of oValue
local to the function call. The reason for this is because you'd actually be changing just a "local" copy of oValue
, and not oValue
itself.