why same code in two technology behaving different [duplicate]

China☆狼群 提交于 2019-11-30 18:33:51

问题


Below is my code snippet in C.

void main(){
 int x = 7;
 x = x++;
 printf("%d",x);
}

output : 8

public static void main(String[] args){

        int x = 7;

        x =  x++;
        System.out.println(x);
    }

output : 7

i am not getting why both language giving different output. I've referred below link What is x after "x = x++"?


回答1:


In java after x++ there is no change in the value of x

x = x++; equal to

int i= x;
x = x + 1;
x = i;

so x remains same as i

You can read more from here :Why are these constructs (using ++) undefined behavior?




回答2:


In the second example the assignment first saves the value of x, then sets x to its value plus 1, and, finally, resets x back to its original value. Kind of:

int temp=x;
x=x+1;
x=temp;



回答3:


x=x++;

This gives arbitrary results in C, mainly depending on compiler. Read about sequential points in C. You may refer to C Programming by Dennis ritchie.



来源:https://stackoverflow.com/questions/17993032/why-same-code-in-two-technology-behaving-different

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