This question already has an answer here:
- What is x after “x = x++”? 17 answers
- explain why difference in the same code [duplicate] 6 answers
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++"?
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?
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;
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