My friend sent me a joke:
Q. What’s the difference between C and C++?
A. Nothing, because: (C – C++ == 0)
I tried to change order and got stuck.
Look at this code:
public class Test {
public static void main(String args[]) {
int c = 10;
System.out.println(c++ - c);
System.out.println(++c - c);
}
}
Why does it return:
-1
0
I understand postfix and prefix increment. Why isn’t this the result?
0
1
Because in the first example,
cstarts out 10.c++incrementscand returns 10, so the secondcnow evaluates to 11 since it was incremented. So the ultimate expression evaluated is10 - 11, which equals -1.In the second example,
++cincrementscagain but returns 12 since it is a pre-increment. The secondcevaluates to 12 as well, since it’s the new value stored inc. So that expression ultimately is evaluated as12 - 12, which equals 0.