that_individual
that_individual

Reputation: 105

Does a for loop create two scopes?

Imagine the following for statement (from an imaginary C-like language) gets desugared into a more simple form:

1| for (int i = 0; i < 10; ++i)
2| {
3|     // do work
4| }

Of course, the sticking point is the int i = 0 in the initializer, beacuse we suppose:

  1. After the loop is done, i is out of scope and we can't reference it.
  2. Upon reaching line 2, a new scope is pushed on the stack and then popped on line 4.

This would mean that this specific for-loop would desugar to:

{
    int i = 0;
    while (i < 10)
    {
        // do work
        ++i;
    }
}

Leading to the creation of a scope for the sole purpose of containing the incrementer variable.

I understand completely that the specifics are implementation defined for any language that permits declarations inside classic-style for loops. I'm just curious if this is how it would work under the covers, at least when creating the initial AST.

Upvotes: 0

Views: 60

Answers (1)

Neutrino
Neutrino

Reputation: 35

I think thats exactly what the compiler does for your. You can see this if you try to compile both codes on LLVM e.g. with clang -S -emit-llvm and compare results.

Upvotes: 1

Related Questions