What is the scope of a while and for loop?
For example, if I declared an object within the loop, what is its behavior and why?
I thought it would be worth mentioning:
Some compilers may have an option which effects the scope of variables created within the for loop initializer. For example, Microsoft Visual Studio has an option /Zc:forScope (Force Conformance in for Loop Scope). 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.
Some compilers may eliminate code it thinks is unnecessary, due to optimization settings and "Dead Store" elimination. For example, if the variable being changed inside the loop isn't read anywhere outside the loop, the loop itself may be discarded by the compiler.
For example, consider the following loop:
int cnt = 0;
int trys = MAX_INT;
while (trys-- > 0)
{
cnt += trys;
}
it is possible that some compilers may discard [the contents of] the loop, because the variable Cnt isn't being used after the loop.