Variable redeclaration in c in loop and outside loop?

In order to understand your problem, also called variable’s scope, let’s see to the following sample program:

#include <stdio.h> 

int main(int argc, char *argv[])
{
    int I = -1;
    for (int I = 0; I < 3; I++) {
        printf("%d\n", I);
    }
    printf("%d\n", I);
    {
        int I = 200;
        printf("%d\n", I);
    }
    return 0;
}

As you can see I declared the variable I three times.

When declared into the loop the result will be the Printing of the following values:

0
1
2

After the for loop when I print again the I variable now I refer to the variable declared outside the for loop, the first one I declaration so the result will be:

-1

Now if I open a new scope with the curly braces and I declare a new variable with the same name but with a different value I will get:

200

I hope my description about the variable’s scope is now clear

Leave a Comment