Course contentsShow
← C
Lesson 943 of 1,21913. Advanced CFree lesson

Implementation-defined behavior vs UB

Implementation-defined behavior vs UB

What you'll learn: How to distinguish between code that behaves consistently on a specific compiler versus code that is fundamentally broken and dangerous.

As you reach the advanced stages of C, you’ll notice the language doesn't always have a single "right" answer for how code should run. Instead, it categorizes "weird" code into two main buckets: Implementation-defined behavior and Undefined Behavior (UB).

The Predictable Stranger: Implementation-defined

Think of implementation-defined behavior like a local law. In the UK, you drive on the left; in the USA, you drive on the right. Both are valid systems, but you must know where you are to avoid a crash.

In C, the standard allows compiler creators (like GCC, Clang, or MSVC) to choose how certain operations work, provided they document it. A classic example is the size of an int. The standard says it must be at least 16 bits, but a 64-bit compiler might make it 32 bits. This isn't an error; it's a choice. Your code will behave consistently on that specific compiler, but it might act differently if you move it to another one.

The Chaos Agent: Undefined Behavior

Undefined Behavior is a different beast entirely. This is like trying to drive a car while blindfolded. There are no laws here. The C standard says, "If you do this, anything can happen." The compiler isn't required to warn you, and the program might crash, delete a file, or—most dangerously—work perfectly fine until the day of a big demo.

Common UB includes accessing an array out of bounds or dereferencing a NULL pointer. Because the compiler assumes UB never happens, it may optimize your code in ways that delete "impossible" logic, leading to "Heisenbugs" that disappear when you try to debug them.

Comparing the Two in Code

#include <stdio.h>
#include <limits.h>

int main() {
    // 1. Implementation-defined: Right-shifting a negative signed integer.
    // Most compilers perform "sign extension," but the C standard lets the 
    // compiler author choose. It is predictable if you read your compiler's manual.
    int a = -5 >> 1; 

    // 2. Undefined Behavior: Signed integer overflow.
    // Adding 1 to the maximum possible int. The C standard does not 
    // define what happens. The program might wrap around, or the 
    // compiler might skip this entire line during optimization.
    int b = INT_MAX + 1; 

    return 0;
}

Key takeaway

Implementation-defined behavior is a documented choice made by your compiler, whereas Undefined Behavior is a programming error that results in unpredictable, lawless execution.