简体   繁体   中英

For loop Auto increment variable

In for(int i=0; i < 5; i++) loop isn't i incremented by i++ already before the printf reads it? If so it should return i=1 right? What's the concept here that returns 0 at first.

public class Application {
    public static void main(String[] args) {

        for(int i=0; i < 5; i++) {
            System.out.printf("The value of i is: %d\n", i);
        }
    }
}

14.14.1. The basic for Statement

BasicForStatement: for ( [ForInit]; [Expression]; [ForUpdate] ) Statement
  • If the Expression is not present, or it is present and the value resulting from its evaluation (including any possible unboxing) is true, then the contained Statement is executed. Then there is a choice:

    • If execution of the Statement completes normally, then the following two steps are performed in sequence:

      • First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the for statement completes abruptly for the same reason; any ForUpdate statement expressions to the right of the one that completed abruptly are not evaluated.

      • Second, another for iteration step is performed.

In your example, it means i++ will be executed after the System.out.printf line.

No, the loop incrementation is computed at the end of the loop body.

The behavior is the same as

 for(int i=0; i < 5; ) {
            System.out.printf("The value of i is: %d\n", i);
           //whatever


           //at the very end; just before exiting the loop 
           i = i + 1;
           // exit the loop
        }

In the for loop first the loop run checking only if the i < 5.Since it is true the its will give access into the loop where still i remains zero(0) and execute the statements inside the loop and then increment i by one (i++).Where then the incremented i will be taken into the consideration of the condition.

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