Using a 'for' loop iterator after the loop exits in C
c, c99, for-loop
Solution
There is nothing wrong in C89, C99, or C11 to access the iteration variable after the `for` statement.
int i;
for (i = 0; i < 10; i++) {
/* Some code */
}
printf("%d\n", i); // No magic, the value is 10
From C99, you can use also a declaration as the first clause of the `for` statement, and in that case of course the declared variable cannot be used after the `for` statement.
Problem
For years, I've gotten in to the habit of not using the value of a `for` loop iterator after the loop exits. I could have sworn that I did this, because it used to produce a compiler warning, but after I was challenged in a recent code review, I was proven wrong. For example, I always did this (NOTE: our code standards prohibit the use of the "break" keyword): ``` int i, result; bool done = false; for (i=0; i<10 && !done; i++) { if (some_condition) { result = i; done = true; } } // Value of i may be undefined here ``` Now, obviously the `result` variable could be removed, if I can rely on the value of i. I thought that because of compiler optimization, you could not rely on the value of the loop iterator. Am I just remembering a phantom teaching? Or is this the standard (specifically regarding GNU C)?