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?
for( int i = 0; i < 10; ++i )
{
string f = "foo";
cout << f << "\n";
}
// i and f are both "gone" now
In the above sample code, both i and f are scoped within the {{ and }} When the closing brace is executed, both variables fall out of scope.
The reason for this is simply that the Standard says so; that's how the C++ language works.
As for motivation, consider that this can be used to your advantage:
for( ...)
{
std::auto_ptr obj(new SomeExpensiveObject);
}
In the above code, we are using an RAII smart pointer to "own" the expensive object we created within the loop. The scoping semantics of the for loop dictate that after each execution of the loop, the object that was created during that iteration will be destroyed.