Here is the code
int& fun(){
static int x = 10;
return x;
}
int main() {
fun() = 30;
cout<< fun();
getch();
}
The output is 30. How does this work?
Here is the code
int& fun(){
static int x = 10;
return x;
}
int main() {
fun() = 30;
cout<< fun();
getch();
}
The output is 30. How does this work?
Let's read it line by line:
int& fun()
declares a function named fun
which returns a reference to an integer variable
{
static int x = 10;
The x
variable is static inside this function. A special place in memory is reserved for it and is initialized with 10
. Every time this function is called x
will get the value stored in that special location.
return x;
}
We return x
and leave the function. Let's go to the main
one:
int main()
{
fun() = 30;
Remember that fun
returns the reference to an int. Here we modify the integer to be 30
. Since this integer has static
allocation every time fun
will be called from now on x
will start with 30
, unless other changes are made.
cout<< fun();
Since x
is 30
that's what you get.
getch();
}
Suggestion: use GDB and trace the program's execution step-by step:
$ gdb ./a.out
(gdb) b main
Breakpoint 1 at 0x40077b: file 1.cpp, line 11.
(gdb) r
Starting program: /tmp/a.out
Breakpoint 1, main () at 1.cpp:11
11 fun() = 30;
We start GDB, set a breakpoint at the begining of main
and start the program.
(gdb) disp fun()
1: fun() = (int &) @0x60104c: 10
Since fun
returns a reference to a static variable I can display it's value at each step in GDB.
(gdb) s
fun () at 1.cpp:6
6 return x;
1: fun() = (int &) @0x60104c: 10
Running a single step we see that we are in func
. This is the place where x
is returned (as a reference) to be attributed 30
.
(gdb) n
7 }
1: fun() = (int &) @0x60104c: 30
Indeed, after leaving the function, x
is 30
.
(gdb)
main () at 1.cpp:13
13 cout<< fun();
1: fun() = (int &) @0x60104c: 30
(gdb) s
fun () at 1.cpp:6
6 return x;
1: fun() = (int &) @0x60104c: 30
(gdb)
7 }
1: fun() = (int &) @0x60104c: 30
(gdb)
main () at 1.cpp:15
15 }
1: fun() = (int &) @0x60104c: 30
(gdb) q
We continue the program's execution and leave GDB (though your question is already answered).
It is straightforward : fun
returns the reference to the static
variable inside the function, which is assigned to 30
by this line:
fun() = 30;
this means, x
inside the function is changed to 30
. What is more? It is 30! You print it by calling again fun()
in the next line.
Note that a static variable lives till the end of the program: it is not destroyed even if the function returns!
The fun
function returns a reference-to an int
type. This way, when you call fun() = 30
, you actually set x
to 30.
This way when you print it out, the fun
function will no longer set it, cause that is a one-off declaration.