For Loop Variable Scope

Hello to everyone!

I was wondering what the scope of variables declared in a for loop. Like, for example,

1
2
3
4
5
for(int i = 0; i < 10; i++) {
//statements
}
//...
cout << i;


would this work? I've seen code with it, and apparently it compiles. Another thing
is with

1
2
3
4
5
for(int i = 0; i < 10; i++) {
int b = 0;
}
cout << b;
cout << i;


This looks like it shouldn't work, or is bad, but I'm not too sure because of the previous code. Thank's in advance for help!
From my knowledge
1
2
3
4
for(int i = 0; i < 10; i++) 
{
//statements
}


This will just loop the inside statement 10 times.
Starting from 0 it will add 1 due to the i++ statement within the for.

So with your second code it should just loop b =0; 10 times not really changing anything.
It should output a 0 followed by a 10.

Correct me if i'm incorrect.
Technically, neither of those should compile. Variables defined in the for statement are valid only for the for statement. From memory, the Microsoft compilers allowed this, but GCC and Clang don't.

The standard says:
6.5.3

3) If the for_init_statement is a declaration, the scope of the name(s) extends to the end of the statement. [ Example:
1
2
3
4
5
6
7
int i = 42;
int a[10];

for (int i = 0; i < 10; i++)
    a[i] = i;

int j = i;  // j = 42 

-- end example]
Last edited on
hello genson! thanks for your reply. And yes, you are right, looping with b = 0 shouldn't do much. Yet what I was trying to ask was how come when I try to print out b on line 4 of my second piece of code, the compiler throws an error saying b is not in scope, while the first piece of code just compiles. Perhaps you could shed some light onto this?
thanks NT3! that's what I'm looking for. and, I checked my compiler, and it was the problem. I was on my windows partition when compiling this.
Topic archived. No new replies allowed.