3

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++"?

Community
  • 1
  • 1
ved
  • 909
  • 2
  • 17
  • 43

3 Answers3

2

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?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

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;
Lavinia
  • 11
  • 2
0
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.

user2550754
  • 884
  • 8
  • 15