开发者

Are these two loops always equivalent

In the Java programming language, are the following two loops equiva开发者_JAVA百科lent for any expression exp and and loop body body? Only side condition should be that the freshly introduced variable b does not appear elsewhere in the method (and does not hide an attribute, ...)

while(exp) {
    body
}

and

for(boolean b = exp; b; b = exp) {
    body
}


Yes, under those assumptions.

The for construct checks the condition before the first iteration, so if b is false, then the body will never be executed. To put it another way, in your code example, exp is evaluated precisely once before each loop iteration, and the result used to decide whether to execute that iteration or not.

But why would you want to write code like this?


No they are not. Make your code readable.

One is for counting

The other one is for waiting for a condition to be true.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜