So I've been reading a C++14 book (it's the latest my library had), and something has been swimming 'round my head although I'm around 100-200 pages deeper than it, but at some point it mentions this slap in the face:
i++ + ++i;
It says to not do this, but I did it anyway. In both Visual Studio C++ and online C++ compilers (specifically onlinegdb), it gives me 3
when int i = 1;
, however when I assign i = i++ + ++i;
, online compilers give me 4
and Visual Studio gives me 5
... Let's see, if i++
increments i
but is the original value, and ++i
increments i
and is the new and improved i
, then if int i = 1;
, we'd be doing:
1 + 2;
And i
would be 3
! Both compilers say this. However i = i++ + ++i;
gives different answers! I wish I could verify this, but I can't compute in my head the assignment and the increments. Maybe that's what the compilers are doing as well, one's assigning then incrementing in the expression and the other's doing the opposite. A spirit sort of PEMDAS vs PEDMAS in action.
So I know this is a literal textbook example of undefined behavior, but I'll ask the question anyway: Is there any use of undefined behavior in practice, is there ever a good reason to use this specific piece of code (there probably isn't because of the monstrous nature of it), and is there anything else to note about this code (and its deal)?