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;
}
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.
Here are the three levels of scope in a C++ program: global, local, and block.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With