How does the this c++ code work -
here code
int& fun(){ static int x = 10; return x; } int main() { fun() = 30; cout<< fun(); getch(); }
the output 30. how work?
let's read line line:
int& fun()
declares function named fun
returns reference integer variable
{ static int x = 10;
the x
variable static inside function. special place in memory reserved , initialized 10
. every time function called x
value stored in special location.
return x; }
we return x
, leave function. let's go main
one:
int main() { fun() = 30;
remember fun
returns reference int. here modify integer 30
. since integer has static
allocation every time fun
called on x
start 30
, unless other changes made.
cout<< fun();
since x
30
that's get.
getch(); }
suggestion: use gdb , trace program's execution step-by step:
$ gdb ./a.out (gdb) b main breakpoint 1 @ 0x40077b: file 1.cpp, line 11. (gdb) r starting program: /tmp/a.out breakpoint 1, main () @ 1.cpp:11 11 fun() = 30;
we start gdb, set breakpoint @ begining of main
, start program.
(gdb) disp fun() 1: fun() = (int &) @0x60104c: 10
since fun
returns reference static variable can display it's value @ each step in gdb.
(gdb) s fun () @ 1.cpp:6 6 return x; 1: fun() = (int &) @0x60104c: 10
running single step see in func
. place x
returned (as reference) attributed 30
.
(gdb) n 7 } 1: fun() = (int &) @0x60104c: 30
indeed, after leaving function, x
30
.
(gdb) main () @ 1.cpp:13 13 cout<< fun(); 1: fun() = (int &) @0x60104c: 30 (gdb) s fun () @ 1.cpp:6 6 return x; 1: fun() = (int &) @0x60104c: 30 (gdb) 7 } 1: fun() = (int &) @0x60104c: 30 (gdb) main () @ 1.cpp:15 15 } 1: fun() = (int &) @0x60104c: 30 (gdb) q
we continue program's execution , leave gdb (though question answered).
Comments
Post a Comment