I'm looking purely at the syntax here, not at the deeper meaning of what the code is trying to achieve.
Below, I've added extra braces which don't affect the meaning, but may help to clarify.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
using std::cin;
using std::cout; using std::endl;
int main()
{
int x = 1, counter = 1;
int pri = 0;
while (counter < 10000)
{
++x;
for (int priCheck = 2; priCheck < x; ++priCheck)
{
if (x % priCheck == 0)
{
pri = 0;
break;
}
else
{
++pri;
}
}
if (pri >= 2)
{
++counter;
}
}
cout << x << endl;
}
|
When the
break
statement at line 19 is executed, it exits from the
for
loop which began at line 14.
Also the original author of this code didn't include curly braces after declaring the for loop. Does the compiler determine the scope of the for loop? |
If there are no curly braces, then the
for
loop will control just a single statement. The important thing is how to determine what is a single statement?
Here, this
if-else
is considered as a single statement,
1 2 3 4 5 6 7
|
if (x % priCheck == 0)
{
pri = 0;
break;
}
else
++pri;
|
Notice how the first part uses braces, that's because there are two statements:
You can see there are two statements, as each one ends in a semicolon. But wrap them in a pair of braces { } it becomes a single compound statement.
Similarly, the whole of the if-else is regarded as a single statement for the purposes of determining the scope of the
for
loop.
This is one reason why indentation is so very important. It doesn't matter to the compiler. It just sees some extra whitesplace which is ignored. But to the human reader, indentation is used as a way of indicating the scope. You can see all the statements controlled by the for loop are indented, and the next statement aligned vertically with the
for
itself is line 27
if (pri >= 2)
and this is not indented because it does not belong to the scope of the
for
loop.