Behaviour of PreIncrement and PostIncrement operator in C and Java [duplicate]

℡╲_俬逩灬. 提交于 2019-12-07 02:37:04

问题


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?


回答1:


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;



回答2:


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



来源:https://stackoverflow.com/questions/17514805/behaviour-of-preincrement-and-postincrement-operator-in-c-and-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!