Reputation: 481
According to my understanding of the C++ specification (according to the draft standard online), a for-loop can be rewritten in terms of a while-loop and a block for initialization. According to my understanding, the iteration statement of the for-loop occurs in the same scope as the body, so it should be able to use variables declared in the body of the for-loop. Both gcc and clang reject the following (contrived) code, which is a simplification of my real code.
I can obviously fix the code by declaring j outside of the loop, but why is j out of scope below?
int main()
{
for(int i=0; i<10; i=j) int j=i+1;
// // I must misunderstand the standard because I thought the above loop is
// // equivalent to the commented code below where j is clearly in scope.
// {
// int i=0;
// while(i<10) {
// int j=i+1;
// i=j;
// }
// }
return 0;
}
According to clang (and gcc), this is invalid.
test.cpp:3:26: error: use of undeclared identifier 'j'
for(int i=0; i<10; i=j) int j=i+1;
^
1 error generated.
Upvotes: 2
Views: 1397
Reputation: 7486
The reason you get error is because 'j' is declared/ initialized inside for loop. But in C++ compilers compile from left to right and top to bottom, so when compiler encounters that 'i' is getting asigned with a garbage value, it pops up an error.
Upvotes: 0
Reputation: 5178
It is somehow obvious. I'll give you an example. Can you write something like this?
int main(){
int i = j * 10;
//Some other lines ...
int j = 2;
return 0;
}
Of course in the given code i and j are in the same scope, but before using j you have to declare it.
You have to consider other things too besides the scope.
Upvotes: 0
Reputation: 504133
For reference, the expansion is as follows (§6.5.3/1). The for-loop statement:
for (init cond; expr) statement
is equivalent to:
{
init
while (cond)
{
statement
expr;
}
}
Upvotes: 1
Reputation: 36102
for(int i=0; i<10; i=j) int j=i+1;
would, if it were valid syntax, be the same as
for(int i=0; i<10; i=j)
{
int j=i+1;
}
the for loop is then accessing 'j' inside the {}
scope which doesn't exist until the first loop is executed. C++ is a static language which depends on the compiler being able to resolve its variables at compile time but what you are doing is trying to make it resolve the variable during runtime.
Upvotes: 3