1

I have this code:

#include <iostream>    
using namespace std;    

int & squareRef(int );    

int main() {  
   int number1 = 8;    
   cout <<  "In main() &number1: " << &number1 << endl;     
   int & result = squareRef(number1);   
   // cout <<  "In main() &result: " << &result << endl;    
   cout << result << endl;   
   cout << result << endl;   
   cout << number1 << endl;
}    

int & squareRef(int  rNumber) {   
   cout <<  "In squareRef(): " << &rNumber << endl;      
   rNumber *= rNumber;    
   return rNumber;    
}   

The program produces the following output:

In main() &number1: 0x28ff08    
In squareRef(): 0x28fef0    
64    
1875681984      
8    

Can anyone please explain why the two "results" are different , is that suppose to be same isn't ?

Jonas Schäfer
  • 20,140
  • 5
  • 55
  • 69
Kumaran Raj K
  • 365
  • 1
  • 11

1 Answers1

4

You are invoking undefined behaviour by returning a reference to a local variable:

test.cc:19:7: error: reference to local variable ‘rNumber’ returned [-Werror=return-local-addr]
 int & squareRef(int  rNumber) {   

rNumber is copied on the stack for the call. After the call, the value on the stack is undefined, and might well change due to subsequent calls. The reference you return only points to that location on the stack and does not hold the actual value.

In general, when these things happen, it is very helpful to turn on all warnings your compiler can give you. With gcc, the flags -Wall -Wextra -Werror provide you with a lot of helpful warnings, such as these. In general, code should compile without throwing any warnings (except maybe unused variables/parameters in function stubs, although there are macros to explicitly skip over these).

Jonas Schäfer
  • 20,140
  • 5
  • 55
  • 69