Undefined behavior


Undefined behavior happens when you break certain rules of C++ in your code. It means that the compiler is allowed to do anything with your code. For example, the compiler may:

  • refuse to compile code and return an error message instead.
  • compile the code successfully, but the program crashes when run.
  • compile the code successfully, but the program produces wrong results when run.
  • compile the code successfully, but the program works on one computer, but crashes on another.
  • compile the code successfully, and the program does exactly what you expect in all cases.
  • etc.

In short, the results of the compilation are unpredictable. A program may appear to run well, but as far as C++ language specification is concerned, the program is broken and even small changes to the environment it runs in may lead to a program crash or to the program returning incorrect results. Thus undefined behavior should be avoided at all costs.

Undefined behavior is not a silly idea as it might look like. Two of the primary goals of C++ are performance and portability. These aims are contradictory: given the variety of microprocessors in the world, it is almost insurmountable task to design a language that allows code to run well on all of them. C++ solves this issue by simply disallowing certain behaviors of the program. Since the compiler may not be able to detect whether those rules are violated, the C++ language allows it to produce more or less broken programs. Therefore, the programmer must be very careful.