cvariablesfor-loopredeclaration

Variable redeclaration in c in loop and outside loop?


When int i; statement is declared 2 times in a program it shows errors but where as when int i; is written in a for loop that runs two times, it does not show any error.

#include<stdio.h>//code 1 showing error
int main()
{
    int i;
    int i;
    return 0;
}
#include<stdio.h>//code 2 no error
int main()
{
    for(int j=1;j<=2;j++)
        int i;
    return 0;
}

Solution

  • 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