Unary operators in java vs c++ [duplicate]

删除回忆录丶 提交于 2019-12-24 13:07:42

问题


Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
Is there any difference between the Java and C++ operators?

Why unary operators give different result in c++ and java?

Check this out:

int i = 1;
i = i++ + ++i;
print i  (with cout or println)

In java: prints 4

In c++: prints 5

Why ?


回答1:


In C++ the behavior of a statement such as i = i++ + ++i; is actually undefined so the fact that the behavior differs is not so surprising.

In fact it shouldn't be surprising if two different C++-compilers produce different behavior for the C++ statement i = i++ + ++i;.

Related question:

  • Why are these constructs (using ++) undefined behavior?
  • When exactly is the postfix increment operator evaluated in a complex expression?



回答2:


it better explained with this code:

int i = 1;
int j =0;
j = i++ + ++i;
print j  (with cout or println)

In java the i++ and ++i have the same result i is incremented by 1 so you do: 2 + 3 = 5 i will be 5 afterwards. j will be 5 afterwards

in c++ i++ and ++i behave differently i++ increments in place while ++i increments afterwards.

so it reads 2+ 2. j will be 4 and i will be 5.




回答3:


C++ and Java are different languages so there is different effect. See operators priority.

In Java ++ (postfix and prefix) are on same line, while in C++ they are with different priority.

  • operators priority in Java
  • operators priority in C++



回答4:


In Java, the post fix increment ++ operator is somewhat "atomic" (not threading related sense) in the sense that the value is evaluated into the expression and the increment happens without the interference of other operators.

Operator precedence table of Java from Wikipedia.

i = i++ + ++i
i = ((i++) + (++i))
i = (1 + (++i)) // i = 2
i = (1 + 3) // i = 3
i = 4

For C, the behavior is undefined by standard.

Operator precedence of C from Wikipedia.




回答5:


i = i++ + ++i;

results in unspecified behaviour, which means you can get different results with different compilers or different compiler settings.




回答6:


int i = 1;
i = i++ + ++i;
System.out.println(i);

int i = 1;
int j = i++ + ++i;
System.out.println(j);

give always 4 because in Java parse expression from left to right (LALR).



来源:https://stackoverflow.com/questions/11311140/unary-operators-in-java-vs-c

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