METABYTE
Back to articles

C puzzle: what is a after a = a++ + ++a?

A classic undefined behavior in C that makes compilers behave like cats on a hot tin roof.

14 mai 20262 min read
C puzzle: what is a after a = a++ + ++a?

Remember those interview questions where you have to compute the value of a variable after a couple of increments? If you do, you either laughed it off or are still wondering what the compiler made of it.

Back in 2011, Polish researcher Gynvael Coldwind posted a deceptively simple example: int a = 5; a = a++ + ++a;. And asked to guess the result. Spoiler: the C standard considers this expression undefined behavior. That means the compiler can do absolutely anything — from formatting your hard drive to sending your code into a black hole.

Why? Because within a single sequence point, the variable a is modified more than once without an intervening sequence point. Both a++ and ++a modify a, and the order of evaluation is unspecified. Different compilers, different optimization flags — different answers. For instance, GCC with -O2 might give 12, while Clang gives 11. And if you're lucky, it might even be 42.

The moral: never write such code in production unless you want to be cursed at daily standups. Use separate expressions and don't rely on evaluation order. And yes, always enable compiler warnings — -Wall -Wextra will save your reputation.

METABYTE studio comment: We also have days when code behaves like this example — unpredictably. But we prefer not to guess on the compiler and instead write clean, understandable code. Although sometimes we're tempted to leave a few such puzzles for future interns...

NEXT STEP

Liked the approach?

We apply the same principles to client projects: AI, automation, products that don't die after launch.