开发者

Does a for loop's while section execute each pass or only once in java?

开发者 https://www.devze.com 2023-01-23 22:50 出处:网络
for example would this be constant 开发者_如何学Pythonor change with each pass? for(int i = 0; i < InputStream.readInt(); i++)

for example would this be constant 开发者_如何学Pythonor change with each pass?

for(int i = 0; i < InputStream.readInt(); i++)


 for(int i = 0;                  // executed once
     i < InputStream.readInt();  // executed before each loop iteration
     i++                         // executed after each loop iteration
    ) {
    ....
 }


The first section is executed once before the looping starts. The second section is checked before every loop and if it is true, the loop gets executed, if false the loop breaks. The last part is executed after every iteration.


It executes every time. The for syntax is sugar for

int i = 0
while(true)
{
    if(!(i < InputStream.readInt()))
    {
        break;
    }
    // for body
    i++
} 


For times when a control-flow diagram is actually the best graphical representation of a concept.

http://upload.wikimedia.org/wikipedia/commons/0/06/For-loop-diagram.png

I think the main issue is the question: does

i < InputStream.readInt(); 

get executed each loop iteration? Yes, it does.

In this case it's not changing any sensitive variable, the only variable actually changing in your code is i, but InputStream.readInt() will be run each iteration to make the comparison and will therefore run readInt() again on InputStream.

What about something like:

for (int i=0; i < xObj.addOne().parseInt(); i++)

(given the method addOne returns a string representation of an integer one greater)

Is my "check" incrementing the value that would be incremented if I called xObj.addOne() like normal? Yes. and does it stay incremented to the next loop iteration? Yes.

It's just like doing

 int x = 0;
 for (int i=0; i < ++x; i++);

This will never terminate, as ++x is always greater than x (which is also i)

What about a nontrivial example?

int x = 6;
for (int i=0; i < x--; i++) {
    System.out.print(i+" ");
}

outputs

0 1 2
0

精彩评论

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