Return out-of-scope reference(?)

Nov 17, 2013 at 2:23am
Howdy,

I'm a little baffled as to why my compiler isn't complaining when I return a reference, which falls out of scope.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int& foo() {
	int a = 10;
	return a;
}

int main(int argc, char* argv[]) {
	int i = foo();
	std::cout << i << std::endl;
	std::cin.get();
	return 0;
}


I'm not compiling with any non-default flags or anything like that. It just seems strange that I'm able to do something this illegal without even a warning. Basically, I guess my question is this : Under which circumstances would this be allowed? Because apparently, it's perfectly fine.
I'm using the VC++2008 express IDE if it makes a difference.
Last edited on Nov 17, 2013 at 2:24am
Nov 17, 2013 at 2:33am
I'm not compiling with any non-default flags or anything like that.

That's probably why -- try upping the warning level in the compiler settings.

With my compiler, I get this:
test.cpp: In function 'int& foo()':
test.cpp:4:6: warning: reference to local variable 'a' returned [-Wreturn-local-addr]
  int a = 10;
      ^
test.cpp: At global scope:
test.cpp:8:5: warning: unused parameter 'argc' [-Wunused-parameter]
 int main(int argc, char* argv[]) {
     ^
test.cpp:8:5: warning: unused parameter 'argv' [-Wunused-parameter]
I haven't tried with MSVC++ yet, but I would hope that they would have a similar warning for it.

EDIT: Yeah, it does:
warning C4172: returning address of local variable or temporary
warning C4100: 'argv' : unreferenced formal parameter
warning C4100: 'argc' : unreferenced formal parameter

This is with the 2010 version, though.
Last edited on Nov 17, 2013 at 2:39am
Nov 17, 2013 at 6:50am
Ah yes, I'm getting a warning now as well. It's strange nonetheless why I should be able to do this in the first place... Thanks for taking the time long double main!
Last edited on Nov 17, 2013 at 6:51am
Nov 17, 2013 at 7:31am
There is one trick to return a variable from inside a function like that though AFAIK by making it static.

1
2
3
4
5
int &foo()
{
    static int bar = 0;
    return( bar );
}
Nov 17, 2013 at 11:39pm
Hmm, why would you wanna do that?
Nov 18, 2013 at 12:37am
What if you wanted to know how many times a function has been called?

1
2
3
4
5
6
7
int &foo()
{
    static int bar = 0;
    function();
    ++bar;
    return( bar );
}


Then you can reset the counter when ever you want.
Nov 18, 2013 at 3:17am
I see. Thanks for the input!
Topic archived. No new replies allowed.