0

I have the following code:

  int x,y,z;
  x=1;y=1;z=1;
  ++y+=x+y+z;
  cout<<y;        // returns 6

  x=1;y=1;z=1;
  ++y+=x+y+z++;
  cout<<y;       //returns 5

Is this undef behavior? In the 2nd example the right side is evaluated first and then the prefix of the left side. If it's not undef behavior can you please point to the precedence/evaluation rule where this belongs.

Peter Green
  • 25
  • 1
  • 6
  • Which version of C++ are you using? – chris Nov 11 '21 at 11:25
  • using version c++17 gcc version 7.3.0 – Peter Green Nov 11 '21 at 11:29
  • Does [this answer](https://stackoverflow.com/a/46171943/962089) make sense? It lightly covers the new C++17 rules, in particular the one that applies here. – chris Nov 11 '21 at 11:32
  • empirical observation: gcc complains about a possibly undefined operation (-Wsequence-point) regardless of `--std` options, clang complains in c++14 mode, is silent in 17 and above. Code compiled with gcc and clang outputs different numbers (6 5 vs. 5 5). –  Nov 11 '21 at 11:37
  • yes thank you chris, it doesn't have a similar example but there are useful information there – Peter Green Nov 11 '21 at 11:47
  • 4
    Even if such questions might be interesting fro academic reasons, why someone would write such unreadable code, especially if most programmers did not really know what is the created behavior. Simply avoid such coding! – Klaus Nov 11 '21 at 13:00
  • @Klaus Could not agree more! Any employee writing such code should be fired on the spot. :) – Marko Popovic Nov 11 '21 at 13:21
  • @MarkoPopovic It is not up to a single coder to do such trash code. It is always part of any review to find such obscurities before such coding goes to production code base. Such code must never pass a review. If such code is part of the production code base, you have definitely a general quality problem in your company. Such coding is a sign for bad ideas. If you find such things, you have to look deeper and will find much more trash! – Klaus Nov 11 '21 at 14:42

0 Answers0