strange behaviour of function returning reference

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  int& valueStatic()
  {
    static int x = 10;
    return x;
  }

  int& valueNonStatic()
  {
    int x = 10;
    return x;
  }


int main()
{
  valueStatic() = 30; // why it works as lValue??
  cout<< " value is  "<<valueStatic();  // why it will print 30??

  valueNonStatic() = 30;
  cout<< " value is  "<<valueNonStatic();  // will print 10??
}


please explain the questions in comments
valueStatic() = 30; // why it works as lValue??

The function returns reference that is lvalue. So the code is correct. However the following function

1
2
3
4
5
  int& valueNonStatic()
  {
    int x = 10;
    return x;
  }


has undefined behaviour.
1
2
3
4
5
int& valueNonStatic()
  {
    int x = 10;
    return x;
  }


i have executed it many times changing the value of x, output is always what we assign to x. guess this is not undefine
ankushnandan wrote:
i have executed it many times changing the value of x, output is always what we assign to x. guess this is not undefine

Executing code with undefined behavior can do anything at all, including printing what you assigned.

When I compile that program (with the missing include/using added), I get
test.cc:13:12: warning: reference to stack memory associated with local variable
      'x' returned [-Wreturn-stack-address]
    return x;
           ^
1 warning generated.


on another compiler
"test.cc", line 13.12: 1540-1103 (W) The address of a local variable or temporary is used in a return expression.


on another compiler
"test.cc", line 13: Warning: Returning a reference to a local variable or temporary.


on another compiler
test.cc: In function ‘int& valueNonStatic()’:
test.cc:12:9: warning: reference to local variable ‘x’ returned [enabled by default]


Test runs:
sun:
 value is  30 value is  30

ibm:
 value is  30 value is  10


but even if every compiler I have available printed 30 (or 10, or 42), it wouldn't make it any less of an error.
Last edited on
Topic archived. No new replies allowed.