-4

Here are two programs. Both of them have a function fun() whose return type is reference to an integer. Only the difference between two functions is that in one function x is declared as static int while in other it is not. The output to the first question is 10 and the output to the second question is 30. How?

Program 1:

#include<iostream>
using namespace std;

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

Program 2:

#include<iostream>
using namespace std;

int &fun()
{
    static  int x = 10;
    return x;
}
int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
thedarkpassenger
  • 7,158
  • 3
  • 37
  • 61

1 Answers1

2

Program 1: you return a reference to a variable which ceases to exist as soon as the function returns, then store the value 30 to that non-existing variable, which may or may not crash your machine. Regardless, the following call to fun() reinitializes a local variable "x" and returns it.

Program 2: A static variable at function scope is kind of like a global variable that's only accessible to that function. You return a reference to that static (which still exists), and set its value. When you call the function again, the static still has the value you assigned to it.

Peter
  • 14,559
  • 35
  • 55