c++ - References - Why do the following two programs produce different output? -
i read references in c++. aware of basic properties of references still not able figure out why following 2 programs produce different output.
#include<iostream> using namespace std; int &fun() { static int x = 10; return x; } int main() { fun() = 30; cout << fun(); return 0; }
this program prints 30
output. per understanding, function fun()
returns reference memory location occupied x
assigned value of 30
, in second call of fun()
assignment statement ignored. consider program:
#include<iostream> using namespace std; int &fun() { int x = 10; return x; } int main() { fun() = 30; cout << fun(); return 0; }
this program produces output 10
. because, after first call, x
assigned 30
, , after second call again overwritten 10
because local variable? wrong anywhere? please explain.
in first case, fun()
returns reference same variable no matter how many times call it.
in second case, fun()
returns dangling reference different variable on every call. reference not valid after function returns.
when use
fun() = 30;
in second case, setting value of variable not valid longer. in theory, undefined behavior.
when call fun()
second time in second case, variable x
set 10
. independent of first call same function.
Comments
Post a Comment