My compiler is giving me a warning as it should about dangling pointer in the function. Can someone explain to me why this would happen. Is &value considered a local variable because it goes out of scope? Making reference variables in fx scope e.g.foo (int &a, int &b) persist after scope of function is closed. What do I need to learn from this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<iostream>
int * foo(int value)
{
value *=value;
return &value;
}
int main()
{
int * value = foo(3);
std::cout<<*value;
return 0;
}
.\src\main.cpp:3:15: warning: address of local variable 'value' returned [-Wreturn-local-addr]
Is &value considered a local variable because it goes out of scope?
No. &value is a temporary. value is a function parameter, and thus local to the function.
If you change the signature to foo(int &), the rest of the code won't compile because you're passing a literal, which is constant. If you change it to foo(constint &) you won't be able to do value *= value. If you remove that assignment, you'll have the same problem you have now, because the call foo(3) creates a temporary that exists in the caller until the callee returns (this is necessary because the function takes the address of the parameter), so the pointed-to value will still no longer exist when control reaches line 14.
Making reference variables in fx scope e.g.foo (int &a, int &b) persist after scope of function is closed.
What?
-sorry
If I pass &a, &b as parameters
foo(int & a, int & b,)
{
a = a-1;
b = b*9000;
}
vars a & b aren't considered local, are they? The parameters ultimately change the argument and can be seen in main after foo is closed. If they are not local vars what are they called?
No they are not local to foo(), but they are local to main().
If they are not local vars what are they called?
You passed the variables by reference, which is very similar to passing by pointer. You are basically passing the address of the variables to the function, not copies of the variables.