Optimizing by taking advantage of undefined behaviour

Undefined behavior doesn't sound like something you'd ever deliberately introduce into a program's codebase. Programmers generally prefer their programs' behaviors to be fully defined - nasal demons are rarely pleasant things.

However, there are sometimes good reasons for adding a statement to your program with undefined behavior. In doing so, you are essentially telling the compiler "I don't care what happens if control flow reaches this point", which allows the compiler to assume that control flow will never get to that point if doing so will allow it to better optimize the parts of the program that you do care about. So it can be an optimization hint.

A good way to use this hint is to put it in the failure path of assert statements. In checked/debug builds, assert works as normal (does the test and terminates the application with a suitable message if the test fails) but in release/retail builds assert checks the test and does something undefined if the test fails. The compiler can then skip generating the code to actually do the test (since it's allowed to assume that it will never fail) and can also assume that the same condition is false in the subsequent code, which (if it's sufficiently smart) will allow it to generate better code.

GCC has a built-in function for just this purpose: the __builtin_unreachable() function is specified to have undefined behavior if it is ever called, and is actually used in just this way. I think this is really clever, in a slightly twisted way.

Leave a Reply