-3

When I run my code, attempting to return a local variable:

#include<iostream>
using namespace std;

int &fun()
{     
  int x = 30;      
  return x;    
}

int main()    
{   
    fun() = 10;   
    cout << fun();    
    return 0;    
}

why does some compiler output 0 and some are 30

Kieren Pearson
  • 416
  • 3
  • 15
Pbox
  • 85
  • 1
  • 1
  • 11

1 Answers1

3

Returning a reference to a local variable that subsequently goes out of scope is undefined behaviour in C++.

Sometimes it might work, sometimes it might not. Occasionally the compiler might eat your cat.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483