Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the scope and priority of variable in c++

Could anybody explains to me why the result is 2, which x is using and why.

auto x = 0;

int f(int i){
    auto x = 1;
    {
        static auto x = 0;
        x += i;
    }
    return x;
}
int main() {
    cout << f(1) + f(2) <<endl;// result 2
    return 0;
}
like image 898
Kaining xin Avatar asked May 11 '20 12:05

Kaining xin


People also ask

What are the scopes of variable in C?

In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.

What are the 3 scope levels in C?

Here are the three levels of scope in a C++ program: global, local, and block.

What is scope rule in C?

The scope rules of this language make the decision that which part of the program a specific piece of code or data item is accessible. Moreover, the identifiers stated in the outermost block of a function comprise the function scope. We can easily access them only in the function that declares them.

What is scope of variable and its types?

A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.


1 Answers

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
like image 119
Cory Kramer Avatar answered Oct 20 '22 00:10

Cory Kramer