C Programming • C17 baseline, standards-specific features labeled
Undefined, Unspecified, and Implementation-Defined Behavior
Recognize behavior the C standard leaves open and avoid relying on accidental compiler or platform outcomes.
Undefined behavior imposes no requirements on the implementation; examples include out-of-bounds access and signed overflow. Unspecified behavior permits one of several outcomes without requiring which one. Implementation-defined behavior requires the implementation to document its choice. Portability depends on distinguishing these cases.
Example
#include <stddef.h>
int get_item(const int values[], size_t length, size_t index, int *result) {
if (values == NULL || result == NULL || index >= length) {
return 0;
}
*result = values[index];
return 1;
}
What to expect
The function checks pointers and the index before reading an array element.
Key idea: Use the standard and compiler diagnostics to identify assumptions; a program appearing to work does not make undefined behavior valid.