What is the scope of a while and for loop?
For example, if I declared an object within the loop, what is its behavior and why?
Check out this code
#include < stdio.h >
int i = 10;
int main() {
for(int i=0; i<3; i++) {
fprintf(stdout," for i = %d & upper i = %d\n",i,::i);
}
while (i>3) {
int i = 30;
fprintf(stdout," while i = %d & upper i = %d\n",i,::i);
i++;
fprintf(stdout," while i = %d & upper i = %d\n",i,::i);
}
fprintf(stdout,"i = %d \n",i);
}
In the code above, the global variable i is different from one which is controlling the for loop.
It will print
for i = 0 & upper i = 10
for i = 1 & upper i = 10
for i = 2 & upper i = 10
when while loop is executed - the variable i defined inside while is having local scope, where as the variable under (i > 3) follows the global variable, and doesn't refer to local scope.
Dipan.