Why doesn't changing the pre to the post increment at the iteration part of a for loop make a difference?

后端 未结 27 2476
-上瘾入骨i
-上瘾入骨i 2020-11-30 06:22

Why does this

 int x = 2;
    for (int y =2; y>0;y--){
        System.out.println(x + \" \"+ y + \" \");
        x++;
    }

prints the s

相关标签:
27条回答
  • 2020-11-30 07:08

    ++i and i++ makes a difference when used in combination with the assignment operator such as int num = i++ and int num = ++i or other expressions. In above FOR loop, there is only incrementing condition since it is not used in combination with any other expression, it does not make any difference. In this case it will only mean i = i + 1.

    0 讨论(0)
  • 2020-11-30 07:08

    Try this example:

    int i = 6;
    System.out.println(i++);
    System.out.println(i);
    
    i = 10;
    System.out.println(++i);
    System.out.println(i);
    

    You should be able to work out what it does from this.

    0 讨论(0)
  • 2020-11-30 07:09

    You are right. The difference can be seen in this case:

    for(int i = 0; i < 5; )
           {
                System.out.println("i is : " + ++i);           
           }
    
    0 讨论(0)
  • 2020-11-30 07:10

    It's a matter of taste. They do the same things.

    If you look at code of java classes you'll see there for-loops with post-increment.

    0 讨论(0)
  • 2020-11-30 07:12

    There are a lot of good answers here, but in case this helps:

    Think of y-- and --y as expressions with side effects, or a statement followed by an expression. y-- is like this (think of these examples as pseudo-assembly):

    decrement y
    return y
    

    and --y does this:

    store y into t
    decrement y
    load t
    return t
    

    In your loop example, you are throwing away the returned value either way, and relying on the side effect only (the loop check happens AFTER the decrement statement is executed; it does not receive/check the value returned by the decrement).

    0 讨论(0)
  • 2020-11-30 07:13

    in a loop, first initialization, then condition checking, then execution, after that increment/decrement. so pre/post increment/decrement does not affect the program code.

    0 讨论(0)
提交回复
热议问题