the scope and priority of variable in c++

The inner x shadows the outer one, but the mutations only apply to the inner most scope

int f(int i){
    auto x = 1;              // consider this "x1"
    {
        static auto x = 0;   // this is "x2"
        x += i;              // mutates "x2" but not "x1"
    }
    return x;                // return "x1" which is still 1
}

Therefore

f(1) + f(2)                  // 1 + 1 == 2

This is all about variable shadowing.

The innermost x in function f is shadowing the automatic x in that function. So that function is equivalent to

int f(int){
    auto x = 1;
    return x;
}

Note furthermore that the x in my abridged version shadows the one at global scope.

The function f is further abbreviated to

int f(int){
    return 1;
}

and now the program output should be obvious.


In fact this function

int f(int i){
    auto x = 1;
    {
        static auto x = 0;
        x += i;
    }
    return x;
}

can be rewritten like

int f(int i){
    auto x = 1;
    return x;
}

because the static variable x declared in this block scope

{
    static auto x = 0;
    x += i;
}

is not used outside the block and does not influence on the returned value of the function. The only side effect of this code block is potential overflowing of the static signed integer variable x that has undefined behavior.

So the both function calls f(1) and f(2) returns 1 and as a result the expression f(1) + f(2) yields 2.

In the program there are declared three variables x. The first one in the global name space

auto x = 0;

The second one in the outer-most block of the function f that hides the declaration of the variable x in the global name space.

auto x = 1;

And the third one is declared in an inner block of the function f

{
    static auto x = 0;
    x += i;
}

that is not visible outside this inner block.