Question:
Java & C/C++ postfix increment: bizarre behaviour?
Andrei
2011-07-11 12:20:58 UTC
This blew me away today!!
I have been programming in C/C++ for quite some time and the following just dazzled me:
int x = 0;
In java the following:
x = x++;
makes x equal 0 while in C/C++ it equals 1;
Tested these 2 on visual studio 2010 and g++, and of course the java vm;
I think i have an idea of why this is the way it is, but what do you guys thing ?
Four answers:
Cubbi
2011-07-11 13:34:03 UTC
While in Java, the statement "x = x++;" is well-defined, In every version of C and C++ it is an ERROR, as severe as accessing an array out of bounds, and equally undetectable by some compilers. There is no answer, no correct value, no explanation for C and C++ compiler behavior when encountering this statement. Any guesses of "this evaluates first, and this second" are likely wrong, unless documented explicitly by the compiler vendor (in practice, many compilers interleave register and memory accesses in ways that leave no clear distinction between "first" and "second", if they decide to generate code at all)



I think it helps to show what happens when different real-life compilers encounter your program:



GNU gcc 4.5.1 on linux/x86_64: 1

GNU gcc 3.4.6 on solaris/sparc: 0

Intel C 11.1 on linux/x86_64: 1

CLang 2.9 on linux/x86_64: 0

MS Visual Studio 2010 on Windows XP/x86: 1

Sun C++ 5.8 on solaris/sparc: 0

Sun C 5.8 on solaris/sparc: 1
deonejuan
2011-07-11 13:00:21 UTC
Depends on the compiler. In ANSI C on the gcc there was a lot of discussion on these Y! Answers about how the prefix ++ is handled (vs. your question about postfix). On the ANSI C, gcc

x = x++; will be a 1 because postfix operator has precedence.



In java the x = x++; is logical just as x = ++x; the assignment ('=') operator has precedence.



I'm surprised if Visual Studio screws for-loops by incrementing before each loop statement.
parrotte
2016-10-23 01:09:55 UTC
c++ means use c interior the present context and after that increment it. (use and then increment) for this reason it quite is used as 5 and then on next assertion in case you println(c) then this is going to coach 6. ++c means increment and use based upon the kind you like it c++ and ++c will coach you ways to.
peteams
2011-07-11 13:14:21 UTC
x = x++;



That intermingles two statements, one says "assign x to itself" and the other says "increment x". The compiler is free to choose what order it does those in. It could assign x to itself and then increment x. It could increment x and then assign x to its original value.



The statement doesn't have a clear meaning, so the compiler is free to implement it in an unclear manner.



It is good programming practice to use simple statements that have no side-effects. Doing so makes code easier to write, easier to read and easier to debug when it goes wrong.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...