简体   繁体   English

For循环自动递增变量

[英]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?for(int i=0; i < 5; i++)循环中,在 printf 读取它之前, i不是已经增加了i++吗? If so it should return i=1 right?如果是这样,它应该返回i=1对吗? What's the concept here that returns 0 at first.这里最初返回0的概念是什么。

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. 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.如果 Expression 不存在,或者它存在并且其评估(包括任何可能的拆箱)产生的值是 true,则执行包含的 Statement。 Then there is a choice:然后有一个选择:

    • If execution of the Statement completes normally, then the following two steps are performed in sequence:如果 Statement 的执行正常完成,则依次执行以下两个步骤:

      • First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right;首先,如果存在 ForUpdate 部分,则表达式按从左到右的顺序计算; 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;如果任何表达式的求值由于某种原因突然完成,for 语句也会因为同样的原因而突然完成; any ForUpdate statement expressions to the right of the one that completed abruptly are not evaluated.突然完成的语句右侧的任何 ForUpdate 语句表达式都不会被计算。

      • Second, another for iteration step is performed.其次,执行另一个 for 迭代步骤。

In your example, it means i++ will be executed after the System.out.printf line.在您的示例中,这意味着i++将在System.out.printf行之后执行。

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.在 for 循环中,循环仅在 i < 5 时才运行检查。因为它是真的,所以它会允许访问循环,其中 i 仍然为零(0)并执行循环内的语句,然后将 i 加一( i++).Where 那么增加的 i 将被考虑到条件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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