Consider the program
#include <stdio.h>
int main(void) {
for (int curr = 0; curr < 3; curr++) {
int prev;
if (curr) {
printf("%d\n", prev); //valid; prev has 0 or 1
}
prev = curr;
}
}
Is it valid?
What's the lifetime and scope of prev?
There will be 3 distinct
prevs with lifetime and scope inside theforloop.
The distinctprevs may (but are not required to) share the same address.
Program is not valid.There will be 3
prevs with lifetime and scope inside theforloop.
Theprevs will share the same address, behaving as if defined withstatic.
Program is valid.There will be 1
prev, as if it was defined outside theforloop.
Program is valid.
Note: question originated during discussion on this answer
