liveBook · Manning

Undefined behavior

As explained in Learn C++ by Example

Undefined behavior is program execution for which the C++ language imposes no requirements on the result.

Undefined behavior occurs when C++ imposes no requirements on an operation's result. One example is integer overflow: adding positive int values eventually exceeds the type's representable range, so the language does not define what happens. section 2.3.4

Overflow can appear to wrap around on a particular implementation, but that observed result is not a portable guarantee. Code that depends on it is relying on undefined behavior rather than a language rule. section 2.3.4

Generating too many rows

A row-generation program adds two previous positive numbers and expects every result to remain positive. Eventually, int overflow can produce a negative value or otherwise escape the assumptions of the program. Checking the generated values with std::all_of, std::none_of, or std::ranges::all_of can expose the failure; an assertion can make the expectation explicit. section 2.3.4

Treat undefined behavior as a boundary to test and avoid:

  • Do not infer portable behavior from a wraparound result observed in Visual Studio. section 2.3.4
  • Check assumptions such as non-negative values while experimenting with generated sequences. section 2.3.4
  • Remember that raw pointers, memory-bound violations, and careless low-level operations can also lead to undefined behavior or crashes. section 1.2

How Learn C++ by Example covers it

How deep it goes
Defines undefined behavior and demonstrates overflow detection, but stops short of cataloguing its causes or explaining compiler internals.
Examples
Uses positive-number row generation, overflowing int values, Visual Studio wraparound, and non-negative checks as practical examples.
What it assumes
Assumes basic C++ integers and sequences while teaching overflow, predicates, lambdas, algorithms, and ranges through the experiment.
What you can do after
Diagnose/debug with it by testing numeric assumptions and recognizing that observed overflow behavior is not portable.
How it connects
Connects undefined behavior with integer overflow, raw pointers, memory bounds, assertions, algorithms, and ranges.

Also explained in

Compare how 7 books explain undefined behavior →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.