C++ Undefined Behavior – Why Doesn’t the Compiler Warn You?

c++undefined-behavior

I was reading the famous Undefined Behavior can cause time travel post and noticed this part:

First of all, you might notice the off-by-one error in the loop
control. The result is that the function reads one past the end of the
table array before giving up. A classical compiler wouldn't
particularly care. It would just generate the code to read the
out-of-bounds array element (despite the fact that doing so is a
violation of the language rules), and it would return true if the
memory one past the end of the array happened to match.

A post-classical compiler, on the other hand, might perform the
following analysis:

The first four times through the loop, the function might return true.

When i is 4, the code performs undefined behavior. Since undefined behavior lets me do anything I want, I can totally ignore
that case and proceed on the assumption that i is never 4. (If the
assumption is violated, then something unpredictable happens, but
that's okay, because undefined behavior grants me permission to be
unpredictable.
)

According to this post the (newer) compiler can already act upon Undefined Behavior at compile-time which means that it is perfectly capable to spot Undefined Behavior in some cases. Instead of letting demons fly out of your nose or spawning dragons by eliminating the UB code or just transforming it because it's allowed to why doesn't the compiler just emit a warning that this is probably not intended?

Best Answer

The work of compiler is to compile the code from high level language to lower level. If you get a descriptive error or warning message, it is the time to thanks to the compiler that it did extra job for you. For getting the required warning, use some static code analysis tool.

And anything not well defined in the spec is undefined, and it is not possible to prepare a comprehensive list of undefined behaviour. Emitting warning on all such behaviours may not be possible.

Practically, in many cases, compilers do warn about undefined behaviours specially with proper warning flags like -W -Wall -Wextra -O2 on gcc. (with optimization flags like -O2 compiler would do regress analysis of code and may generate more warning)