Question

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?

Was it helpful?

Solution 2

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;

OTHER TIPS

The C++ example evokes undefined behavior. You must not modify a value more than once in an expression. between sequence points. [Edited to be more precise.]

I'm not certain if the same is true for Java. But it's certainly true of C++.

Here's a good reference:
Undefined behavior and sequence points

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top