Using undefined behavior for efficient design
In this section, we are going to talk about UB not as it is specified by the standard and applies to C++, but as it is specified by you, the programmer, and applies to your software. To get there, it is helpful first to consider UB from a different point of view.
All the examples of UB that we have seen so far can be divided into two kinds. The first kind is code such as ++k + k
. These are bugs, since such code has no defined behavior at all. The second kind is code such as k + 1
, where k
is a signed integer. This code is everywhere, and most of the time, it works just fine. Its behavior is well defined except for certain values of the variables.
In other words, the code has implicit preconditions: as long as these preconditions are satisfied, the program is well behaved. Note that in the larger context of the program, these preconditions may or may not be implicit: the program may validate the inputs or intermediate results and...