In C++, the terms undefined behavior, unspecified behavior, and implementation-defined behavior refer to different scenarios that can occur during program execution where the outcome cannot be reliably predicted by the C++ standard.
Undefined behavior refers to operations for which the standard provides no definition, meaning that the compiler can do anything it wants—including crashing the program, producing unexpected results, or simply ignoring the operation altogether.
Example: Dereferencing a null pointer.
int* p = nullptr;
*p = 10; // Undefined behavior
Unspecified behavior means that the C++ standard allows for multiple valid implementations or outcomes, but does not require that the behavior must be the same every time. The results may vary across different executions.
Example: The order of evaluation of function arguments.
void func(int a, int b);
func(getValue(), getValue()); // The order of `getValue` calls is unspecified
Implementation-defined behavior refers to choices made by the compiler implementation itself that may affect program behavior, but the standard requires the implementation to document these choices.
Example: The size of the `int` type may vary between implementations.
std::cout << "Size of int: " << sizeof(int) << std::endl; // Implementation-defined
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?