while (status)
for (int i = 0; i < 3; i++)
Is the following syntactically correct:
for (int i = 0; i < 3; i++ && status)
I am trying to have the for loop break early if status is true.
while (status)
for (int i = 0; i < 3; i++)
Is the following syntactically correct:
for (int i = 0; i < 3; i++ && status)
I am trying to have the for loop break early if status is true.
Syntactically, you might want to use:
for (int i = 0; i < 3 && status; i++)
which is valid.
Some consider it bad form though, as it leads to more complicated loops and annoyed maintenance programmers. Another alternative you might want to explore would be:
for (int i = 0; i < 3; i++) {
if (!status) { break; }
}
"I am trying to have the for loop break early if status is true. " The preferred way to do this is with an if statement in the body of the for loop.
for (int i = 0; i < 3; i++) { if(status) break; }
Syntactically correct yes. But the meaning is different. The first piece of code, run your for loop while status is equal to 1. The second piece of code, run only the for loop for 10 times and then exits.
I suspect the following is syntactically correct:
for (int i = 0; i < 3; i++ && status)
but its probably not what you mean. As pointed out by Adam, you probably want:
for (int i = 0; i < 3 && status; ++i)
This has all the meaning you want and all the details of the loop conditions are in the for
statement.
The alternative form:
for (int i = 0; i < 3; i++) {
if (!status) { break; }
}
is useful if you want some code before or after the if
, but the if becomes less visible to the maintenance programmer.
Note:
With status
in the for
statement, the loop may never run if status is false.