Toilet Paper #56

Undefined behavior in C, Objective C, and C++

Problem: What is the result of i = ++i + i++?

Anything can happen: the standard imposes no requirements. The program may fail to compile, may execute incorrectly (crashing or silently generating incorrect results), or may do exactly what the programmer intended. The exact behavior is undefined!

The resulting behavior depends upon not only the specific hardware, platform, and compiler but also on specific settings (optimization level, debug/ release version) of the same compiler. This results in code that is not portable and bugs that are hard to detect.


To get rid of undefined behavior we should understand the concept of sequence point. According to the C standard there is a sequence point

  1. at the end of each full expression (typically, at the semicolon ; )
  2. after the evaluation of all function arguments and before execution of the function body
  3. after the evaluation of the expression a, using the built-in (non-overloaded) operators

a && b

a || b

a? b : c

a , b

There are two main cases with undefined behavior between two sequence points

i = i++ + 1;       // undefined behavior 
i = ++i + 1;       // undefined behavior (well-defined in C++11)
++++i;             // undefined behavior (well-defined in C++11)
f(++i, ++i);       // undefined behavior
f(i = -1, i = -1); // undefined behavior
Solution: between two sequence points the value of a scalar object shall be modified at most once.
cout << i << i++; // undefined behavior 
a[i] = i++;       // undefined behavior
Solution: between two sequence points the prior value of a modified scalar object shall be accessed only to determine the value to be stored.

Further aspects

  • Enable and heed compiler warnings
  • Use static analyzers (like clang’s, cppcheck, etc.) to get even more warnings
Undefined behavior in C, Objective C, and C++

Wir verwenden Cookies, um unsere Webseite für Sie zu optimieren. Mit dem Besuch unserer Webseite erklären Sie sich damit einverstanden. // Our website is using cookies to improve your experience. By continuing to browse the site, you are agreeing to our use of cookies.

Weitere Informationen finden Sie in unserer Datenschutzerklärung. // For more information, please refer to our privacy policy.