2 ms·
Assuming undefined behavior is impossible is a way for the compiler to optimize code. In fact, it is the main reason why UB exists. It is exemplified by the C+
by GuB-42 4y ago
Assuming undefined behavior is impossible is a way for the compiler to optimize code. In fact, it is the main reason why UB exists.
It is exemplified by the C++23 std::unreachable() function, its description is "invokes undefined behavior". It is intended to mark part of the code that are unreachable, so that they don't appear in optimized builds, but may appear in debug builds. It is an explicit use of "the power of UB", an optimizing compiler considers that calling std::unreachable() is impossible, so all code paths that lead to it can be safely pruned. In an debug build, the code may be generated anyways, and the compiler will chose something sensible for what happens when it is called, typically a crash, but it can be anything, it is UB.