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

· coding · Source ↗

TLDR

  • a = a++ + ++a in C/C++ invokes undefined behavior twice, producing three compiler-valid answers: 11, 12, or 13.

Key Takeaways

  • Two UB sources: unspecified fetch order of a operands, and whether post-increment applies before or after assignment.
  • Cross-compiler table (gcc, clang, MSVC, Keil, SDCC, Java, C#) shows results splitting between 11-14 depending on toolchain and version.
  • Java and C# are fully defined: strict left-to-right evaluation means Java always returns 11, C# always returns 11.
  • C# spec §7.3 and Java JLS §15.7 explicitly guarantee evaluation order, making this a non-riddle in those languages.
  • Overloaded operators in C++ (g++, MSVC) can produce different results than built-in int for identical expressions.

Hacker News Comment Review

  • Consensus: the post understates UB severity – three possible answers implies bounded behavior, but true UB allows segfaults, nasal demons, or anything; no result is “correct.”
  • Commenters trace the root cause to C’s design goal of accommodating diverse hardware and dumb compilers, which made evaluation order intentionally unspecified to allow architecture-specific calling conventions.
  • The post resurfaces a real pedagogical harm: C/C++ textbooks (notably in India’s CS curriculum) treated these as exam questions with definite answers, misleading generations of students.

Notable Comments

  • @Boxxed: “if you invoke undefined behavior any result at all is possible” – the article’s three-answer framing is itself misleading.
  • @jcranmer: on gcc, argument evaluation order for f(a(), b()) is ABI-dependent, illustrating why C left this unspecified across architectures.

Original | Discuss on HN