I understand that {...}
introduces a new scope, which is why the following would not work:
for(int i = 0; i < 10; i++) {
// Do something...
}
cout << i << endl; // Error: i is not defined in this scope
However, I'm getting the same error when I try the same thing without braces.
for (int i = 0; i < 10; i++) continue;
cout << i << endl; // Same error, not sure why
I expected i
to be defined in the 2nd example, because there are no {...}
to introduce a new scope.
Any control structure (if
, for
, while
, etc.) without braces applies only to the next statement. The second example is equivalent to the following:
for (int i = 0; i < 10; i++) {
continue;
}
cout << i << endl;
Note that it's often considered bad style to have control structures without braces, because people can forget to add the braces if they add another line, and it can lead to the dangling else problem.