开发者

Can you place a complex condition into a for loop?

开发者 https://www.devze.com 2022-12-15 13:36 出处:网络
while (status) for (int i = 0; i < 3; i++) Is the following syntactically correct: for (int i = 0; i < 3; i++ && status)
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; }


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.


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.


Instead of setting status to true you should just use "break".

0

精彩评论

暂无评论...
验证码 换一张
取 消