2

x=x++ gives different results for C and Java? First is compiled in Visual Studio and the other one is in Eclipse. Why results are different?

#include <stdio.h>

int main(void) {

int x=5;
x=x++;
printf("%d",x);
getch();

}

OUTPUT: 6

public class Test {

public static void main(String[] args) {

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

}

OUTPUT: 5

Lyrk
  • 1,936
  • 4
  • 26
  • 48
  • 2
    behavior of `x=x++` is undefined in `c` – VoidPointer Jun 17 '13 at 09:31
  • 3
    Because that's how it is. In Java you see the result immediately, in C it'll undefined. – Maroun Jun 17 '13 at 09:31
  • Note that the behaviour is well-defined in Java whereas it isn't in C++. – Axel Jun 17 '13 at 09:40
  • did you try x++; instead of x=x++;? – Hisham Jun 17 '13 at 09:43
  • Indeed I am in a java course and teacher give this example and told that it prints 5 but I did not understand why it is 5. I have C background when I compile in C, it gives 6. It must be 6 also to my understanding. – Lyrk Jun 17 '13 at 10:19
  • @user1939432 read this [If i == 0, why is (i += i++) == 0 in C#?](http://stackoverflow.com/questions/13516689/if-i-0-why-is-i-i-0-in-c) to under reason in Java – Grijesh Chauhan Jun 17 '13 at 10:20
  • Because it doesn't say anywhere that it should be the same. Not a real question. – user207421 Jun 17 '13 at 10:22
  • Not a real question? Are you joking or what? This is the first lesson of the course and I do want to learn the execution difference between java and c. This is disgusting for me and I HAVE TO learn why it occurs like this. What is a reasonable question to you? Please tell me and teach me. – Lyrk Jun 17 '13 at 10:30
  • You may well have to learn the differences, but that doesn't have to involve being surprised or disgusted that there are differences. If that's really the question you're being asked you should complain. The only answer is that the languages are defined differently, which is really just a form of begging the question. – user207421 Jun 17 '13 at 10:43
  • The *most important* thing to take from such questions is: writing such code is *a bad idea in all languages*. In C and C++ it's *especially* bad, because the result is undefined. In Java and C# (and I assume many other modern languages) it's defined, but it's still pretty unreadable. – Joachim Sauer Jun 17 '13 at 10:49

0 Answers0