Search code examples
javasyntaxoperator-precedence

"C - C++" joke about postfix/prefix operation ordering


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

Solution

  • Because in the first example, c starts out 10. c++ increments c and returns 10, so the second c now evaluates to 11 since it was incremented. So the ultimate expression evaluated is 10 - 11, which equals -1.

    In the second example, ++c increments c again but returns 12 since it is a pre-increment. The second c evaluates to 12 as well, since it's the new value stored in c. So that expression ultimately is evaluated as 12 - 12, which equals 0.