2

When attempting a competitive programming question small issue was there for me. code:

#include<iostream>


int main(){
    int x = 5;

    x = x++;

    std::cout << x;

    return 0;
}

When i tried on gcc 6.3 in cmd in my system the output was:

5

When my mate tries to run on turbo c on his system output was:

6

What is this unexpected behavior and why turbo c on his system runs that code.

Is it a gcc version difference?

Nitish
  • 565
  • 4
  • 16
  • duplicate https://stackoverflow.com/q/4176328/251311 ? – zerkms Jan 19 '19 at 06:31
  • 7
    `x = x++;` is **undefined behavior** (prior to C++17, IIRC) – Remy Lebeau Jan 19 '19 at 06:33
  • @RemyLebeau this should be the actual answer? – Soumya Kanti Jan 19 '19 at 06:37
  • "`x = x++;`" - what do you expect to happen here ? Why would you want to write something like that ? – Sid S Jan 19 '19 at 06:38
  • @SidS While this does not make sense in the real world, it is a valid expression nevertheless. So it is a good question *why* there are differences in compilers. This might be extended as a pointer example as well. So it could be interesting to predict what happened if 2 pointers point to the same address. – Pinke Helga Jan 19 '19 at 06:42
  • @SoumyaKanti It should. However, I'ld like to see a more verbose answer with a link to spec. It is not naturally clear, whether the expression `x++` should be evaluated, then post increment is done, after all evaluations the result is assigned *or* the entire expression is evaluated, then assigned and finally post increments are done. `y = x++ + x++` could be another test case. – Pinke Helga Jan 19 '19 at 06:59
  • @RemyLebeau Could you write a complete answer referencing the specs or point out where this special case is treated in the given duplicate link above? – Pinke Helga Jan 19 '19 at 07:07
  • 1
    @Quasimodo'sclone it's not a valid expression in C++14 (which OP has specified via tags) – M.M Jan 19 '19 at 08:29

0 Answers0