Pre and post increment in java [duplicate]

孤者浪人 提交于 2021-02-05 12:36:48

问题


I know how pre and post increment operators work, but recently I found out a strange behavior in Java. What i knew so far was (as explained in this answer as well):

a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)

which clearly shows that the ++a returns the value after increment, a++ returns the value before increment. But very recently, I came across this piece of code:

int a = 0;
int b = a++;
int c = ++b;
System.out.println("b=" + b + "\nc=" + c);

The output to this piece of code is:

b=1
c=1

which is strange as a++ should return 0, and increment a, keeping the value of b to 0, as evident from the answer quoted above, while in the next line, b should be incremented first before the value is assigned to c, making it 1. What is happening here?


回答1:


When int b = a++ is called, the value of a (0) is assigned to b (now 0), and then a is incremented to 1.

So, when int c = ++b is called, b is 0. b is then incremented to 1 (by ++b) and then its value is assigned to c.

At the end, b=1 and c=1




回答2:


What exactly you find as strange as it is the expected behavior...

int a = 0; // declare a
int b = a++; // declare b with the value of 0, a becomes 1 afterwards.
int c = ++b; // both c and b gets 0++ here -> 1

System.out.println("b=" + b + "\nc=" + c); prints the expected output.

b=1
c=1


来源:https://stackoverflow.com/questions/52954113/pre-and-post-increment-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!