简体   繁体   中英

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

例如,这是恒定的还是每次通过都会改变?

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
    ) {
    ....
 }

It executes every time. The for syntax is sugar for

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM