compiler warning

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?

Since value is passed by value (a copy), yes it is local to the function.

Making reference variables in fx scope e.g.foo (int &a, int &b) persist after scope of function is closed.

What?

What do I need to learn from this?

Don't return pointers local variables.
Function foo receives a copy of an int.
This copy is named value.
This copy will cease to exist when the function ends.

So you are returning the address of a variable that is about to cease to exist. This is, as you surmise, bad.

What do I need to learn from this?

Don't return the address of variables that are about to cease to exist.

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(const int &) 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?

int main()
{
int a =10;
int b = 20;

foo(a,b);

cout<<a<<"\t"<<b;
vars a & b aren't considered local, are they?

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.
Thank u for your time
Topic archived. No new replies allowed.