Reputation: 45
Output wrt my reasoning should be 0456 but the compiler shows 0415 and I debugged it a little and realised it is targeting both "i" differently.
I'll be grateful if someone can explain the reasoning behind it. Thank You :)
#include <iostream>
using namespace std;
int main()
{
static int i;
for(int j = 0; j<2; j++)
{
cout << i++;
static int i = 4;
cout << i++;
}
return 0;
}
Upvotes: 2
Views: 108
Reputation: 73186
You should expect the output to be as follow:
0
(top-level block scope i
) followed by 4
(for loop block scope i
).1
(top-level block scope i
) followed by 5
(for loop block scope i
).Thus 0415
.
static int i; // declares i at block-scope; denote as (i1)
for(int j = 0; j<2; j++)
{ // enter nested block scope
cout << i++; // at this point, `i` local to current
// block scope is yet to be declared.
// thus, this refers to (i1)
static int i = 4; // this declares a local `i` (denote as (i2))
// which shadows (i1) henceforth
cout << i++; // this refers to (i2)
}
Even if the lifetime of the local static variable i
starts at first loop pass (the first time control passes its declaration) such that its declaration is skipped on the second pass, this does not affect the scope of it.
Block scope
The potential scope of a name declared in a block (compound statement) begins at the point of declaration and ends at the end of the block [...]
Upvotes: 6