Post increment operator not incrementing in for loop

前端 未结 5 1699
我在风中等你
我在风中等你 2020-11-28 13:04

I\'m doing some research about Java and find this very confusing:

for (int i = 0; i < 10; i = i++) {
  System.err.print(\"hoo... \");
}

5条回答
  •  旧巷少年郎
    2020-11-28 13:24

    You're using post-increment: i = i++;, it means something like this:

    temp = i;
    i = i + 1;
    i = temp;
    

    because 15.14.2 Postfix Increment Operator ++:

    The value of the postfix increment expression is the value of the variable before the new value is stored.

    That is why you have the old value.

    For-loop done right:

    for (int i = 0; i < 10; i++) {
      System.err.print("hoo... ");
    }
    

提交回复
热议问题