Advertisement
Beginner C++, Undefined Behavior

What is the difference between undefined, unspecified, and implementation-defined behavior?

Short answer

Undefined behavior has no constraints—anything may happen (must be avoided). Unspecified behavior has several allowed outcomes and the implementation need not document which (e.g., order of evaluation of function arguments).

Save C++ mock interview
Advertisement
AModel answer
Undefined behavior has no constraints—anything may happen (must be avoided). Unspecified behavior has several allowed outcomes and the implementation need not document which (e.g., order of evaluation of function arguments). Implementation-defined behavior is unspecified but the implementation must document its choice (e.g., sizeof(int)). Only UB is dangerous; the others are just non-portable in defined ways.
Real-world example
sizeof(long) is implementation-defined, argument evaluation order is unspecified, and a[5] on a size-3 array is UB.
Likely follow-ups
  • Which must the implementation document? | Which one is dangerous?
Related topics