2

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;
}
klutt
  • 30,332
  • 17
  • 55
  • 95
kooru_hi
  • 43
  • 5
  • 3
    *"Why is it possible to define a variable inside a loop in C?"* - Because it's a very practical thing to do. – klutt Feb 13 '21 at 13:32
  • 1
    Somebody asked this very question about C++. The accepted answer has a nice illustration with functions, of the same principle https://stackoverflow.com/q/66124034/817643 – StoryTeller - Unslander Monica Feb 13 '21 at 14:09

3 Answers3

2

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.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Silidrone
  • 1,471
  • 4
  • 20
  • 35
  • 5
    Lifetime is not actually the issue here; scope is. – Eric Postpischil Feb 13 '21 at 13:40
  • 1
    So it is a different scope in each iteration? I wasn't sure so I did not want to say that and technically sound incorrect so I used "lifetime". – Silidrone Feb 13 '21 at 13:57
  • 3
    Scope does not have anything to do with program execution, including iterations of loops. Scope is **where** in program source code an identifier is visible. Lifetime is **when** during program execution an object exists. Essentially, one identifier cannot refer to two different things in one scope. A declaration in an inner scope is allowed to hide a declaration of the same identifier in an outer scope, but that does not work within the same scope. – Eric Postpischil Feb 13 '21 at 14:12
  • So, can I think of `for (int i = 0; i < 2; i++) {int number = 5; printf("Hello World);}` as the same thing with `{int number = 5; printf("Hello World");} {int number = 5; printf("Hello World");}` ? – kooru_hi Feb 13 '21 at 14:16
  • 1
    @kooru_hi Yes I think you can – Silidrone Feb 13 '21 at 14:21
2

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.

John Bode
  • 119,563
  • 19
  • 122
  • 198
1

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.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
E-Caps
  • 31
  • 4