سؤال

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 ?

هل كانت مفيدة؟

المحلول

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:

نصائح أخرى

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.

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.

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.

i = i++ + ++i;

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

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).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top