In the code I posted, the variable "running" is being shadowed.
When you declare int running = 1, a *new* memory location is allocated. The outer "running" variable (above the loop) is NOT the same variable as the inner "running" variable (declared inside the loop). You can increment/decrement/assign values to/etc... the *inner* "running" variable and it won't change the *outer* "running" variable. Problem is, the while condition is checking the outer variable, whereas within the loop you're modifying the inner variable.
Check it out:
Code:
int main() {
int running = 1;
int count = 4;
printf("The value of (outer) running is %i", running); // will print 1
while (running++ < count) {
int running = 0;
printf("The value of (inner) running is %i", running); // will print 0
}
printf("The value of (outer) running is %i", running); // will print 5
}
[rocket357@FreeBSD ~]$ ./a.out
The value of (outer) running is 1
The value of (inner) running is 0
The value of (inner) running is 0
The value of (inner) running is 0
The value of (outer) running is 5
[rocket357@FreeBSD ~]$
The reason this prints values 1, 0, 0, 0, 5 is because within the loop, "running" is a different variable than "running" that the while condition checks (the outer "running" variable). (Note that the while condition increments the *outer* running variable as evidenced by the last printf).
Now without the shadowed variable:
Code:
int main() {
int running = 1;
int count = 4;
printf("The value of (outer) running is %i", running);
while (running++ < count) {
printf("The value of (inner) running is %i", running);
}
printf("The value of (outer) running is %i", running);
}
[rocket357@FreeBSD ~]$ ./a.out
The value of (outer) running is 1
The value of (inner) running is 2
The value of (inner) running is 3
The value of (inner) running is 4
The value of (outer) running is 5
[rocket357@FreeBSD ~]$
Without the shadowed variable, the "outer" variable is the only one available, so it is used in the inner printf calls.
The fix is simple: check to make sure you aren't shadowing "running".