kooru_hi
kooru_hi

Reputation: 65

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;
}

Upvotes: 2

Views: 179

Answers (3)

John Bode
John Bode

Reputation: 123448

Redfinition errors are a compile-time issue, not a runtime issue. You don’t get a redefinition error in the loop because you only have one declaration for number within that scope.

In the second snippet you have two declarations for number within the same scope, hence the error.

Upvotes: 2

Silidrone
Silidrone

Reputation: 1571

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.

Upvotes: 2

E-Caps
E-Caps

Reputation: 31

Basically, creating a variable inside a loop will make the variable's scope stay in this very loop. "number" does not exist outside of your loop.

Upvotes: 1

Related Questions