Int a = 5; a = a++ + ++a; a =? (2011)

· coding · Source ↗

TLDR

  • a = a++ + ++a with a=5 in C/C++ produces 11, 12, or 13 depending on compiler due to two distinct undefined behaviors around evaluation order.

Key Takeaways

  • Two UBs combine: unknown fetch order for operands, and whether post-increment result survives or is overwritten by the assignment.
  • The four UB combinations map to results 11, 12, 12, 13 – with 12 reachable two ways, explaining its frequency in empirical results.
  • Empirical table across gcc (2.95-4.6), clang, MSVC, Intel C++, Keil, SDCC, PHP, Java, and C# shows real divergence: gcc clusters at 12/13, clang at 11/12.
  • Java and C# are not affected: both specs mandate strict left-to-right evaluation, making the result deterministic (11 for a = a++ + ++a).
  • Overloaded operator results in MSVC and g++ differ from their non-overloaded counterparts, adding another axis of divergence.

Hacker News Comment Review

  • Strong consensus that invoking UB means any output is valid – including segfaults – not just the three values the post enumerates; the post’s framing of “three correct answers” is itself incorrect.
  • Commenters with Indian CS backgrounds note this class of question persisted in university exams and textbooks for years, taught as having a definitive answer.
  • The historical reason C left this undefined is compiler and architecture diversity: evaluation order was left flexible so compilers could match calling conventions and hardware without extra coordination.

Notable Comments

  • @Boxxed: “if you invoke undefined behavior any result at all is possible” – the post’s three-answer framing understates actual UB scope.
  • @bombcar: proposes a middle category of “unspecified behavior” where a compiler must pick one value but is not constrained to which.
  • @HelloNurse: “The final value of a is that if you write this you are fired.”

Original | Discuss on HN