How does this piece of C++ code work?

2020-05-09 17:07发布

问题:

I saw this below example in Geek For Geeks.

#include<iostream>
using namespace std;

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

Answer is 30.

But i am unable to map, how this value is arrived at. Please help me as to how this piece of code works.

After some answers from experts, i got to know the value assigned to function is assigned to static variable x which is equivalent to fun()::x =30

Now, i tried a different piece of code.. where in i have 2 static variables inside the fun() and returning the second variable reference. Still the answer is 30. Is is because when, fun() is assigned, it assigns the value 30 to all the variables inside fun()?

Second piece of code is

#include<iostream>
using namespace std;

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

回答1:

fun returns a reference (int&) to the static variable x inside funs scope. So essentially the statement fun() = 30 is fun::x = 30. Note this is only safe because x is static.



回答2:

function local static variables get initialized the first time into the function and persist until the end of the program. So when you call

fun() = 30;

You return a reference to that variable and then assign 30 to it. Since the variable is still alive it will keep that value. Then

cout << fun();

Is going to return the variable again. Since it was already initialized it will not reset its value and it returns 30 as that is what it was set to in the preceding line.