Does a for loop create a new scope?

Does a for loop create a new scope?

In fact, you don’t even need a loop to create a new scope….

  • Yes, and a in the while loop is created and destroyed each iteration as well.
  • I wouldn’t say that the /variable/ is destroyed… just that it’s value is reset.
  • According to C++ the object is actually destroyed.

Can a variable declared within a for loop still be used after the loop is complete?

Yes, the variable is created and destroyed N times, unless the compiler optimizes it somehow (which it can, I believe). It’s not a very big deal when you have just one int though. It becomes more problematic when you have some complex object recreated 99 times inside your loop.

How are variables scoped in a selection statement?

Loops and selection statements do have their own rules for the variables created as a part of the loop or selection statement itself. These are just designed according to whatever the designer felt was most useful. Anything declared in the loop is scoped to that loop and cannot be accessed outside the curly braces.

Why is the scope of a for loop limited?

Destruction of the variables inside the for loop body occurs before i is incremented. As for why; loops actually take a single statement for their body, it just happens that there’s a statement called a compound statement created by curly braces. The scope of variables created in any compound statement is limited to the compound statement itself.

Where is the for loop scope in C + +?

It defaults to standard c++ behavior. However, this can be changed so that the for loop variable is kept alive outside the for loop scope. If you are using VS it might be useful to be aware that this option exists so you can make sure its set to the desired behavior. Not sure if there are any other compilers which have this option.

Where does the variable go in the loop?

The variable is within the scope of the loop. I.e. you need to be within the loop to access it. It’s the same as if you declared a variable within a function, only things in the function have access to it. Thanks for contributing an answer to Stack Overflow!