Search code examples
javacpost-incrementpre-increment

Behaviour of PreIncrement and PostIncrement operator in C and Java


I'm running the following programs in Visual C++ and Java:

Visual C++

void main()
{
    int i = 1, j;
    j = i++ + i++ + ++i;
    printf("%d\n",j);
}

Output:

6

Java:

public class Increment {
    public static void main(String[] args) {
        int i = 1, j;
        j = i++ + i++ + ++i;
        System.out.println(j);
    }
}

Output:

7

Why the output in these two languages are different? How both the langauges treat pre and postincrement operators differently?


Solution

  • In C/C++ behavior is undefined because In this expression i is modified more then once without an intervening sequence point. read: What's the value of i++ + i++?

    Of-course in Java behaviour of this kind of codes is well defined. Below is my answer for Java, step by step:

    At the beginning i is 1.

    j = i++ + i++ + ++i;
    // first step, post increment
    j = i++ + i++ + ++i;
    //  ^^^
    j = 1   + i++ + ++i;
    // now, i is 2, and another post increment:
    j = i++ + i++ + ++i;
    //  ^^^^^^^^^
    j = 1   + 2   + ++i;
    // now, i is 3 and we have a pre increment:
    j = i++ + i++ + ++i;
    //  ^^^^^^^^^^^^^^^^
    j = 1   + 2   +   4;
    j = 7;