Search code examples
cloopsredefinition

Why is it possible to define a variable inside a loop in C?


Why doesn't this code give a redefinition error:

int main(void)
{
    for (int i = 0; i < 2; i++)
    {
        int number = 5;
    }
}

while this code does:

int main(void)
{
    int number = 5;
    int number = 5;
}

Solution

  • In the first code, the scope of number begins when execution reaches the opening of the for loop and ends when execution reaches the closing of the for loop. In this case, the body of the for loop is executed two times, and number is created and destroyed two times, and has two disjoint scopes. In the second code, the scope aren't disjoint as previous number is still persisting it's lifetime when the second one is defined, and they are in the same scope, so it's a re-definition error.