0

Why this code is printing '0'? Shouldn't it print '20' as reference to local variable 'x' is being returned?

#include<iostream>
using namespace std;

int &fun()
{
    int x = 20;
    return x;
}
int main()
{
    cout << fun();
    return 0;
}

1 Answers1

1

The program has undefined beahaviour because it returns a reference to a local object that in general will be destroyed after exiting the function.

A correct function implementation can look like for example

int & fun()
{
    static int x = 20;
    return x;
}

or

int & fun( int &x )
{
    x = 20;
    return x;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335