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

What 'Undefined Behavior' actually means

What 'Undefined Behavior' actually means

What you'll learn: Why the C standard leaves some errors "unsolved" and how the compiler reacts when you break the rules.

In most languages, if you do something illegal—like accessing the 10th element of a 5-element array—the program crashes with a helpful error message. In C, we enter the realm of Undefined Behavior (UB).

The Contract

Think of the C Standard as a legal contract between you and the compiler. The contract says: "As long as you follow the rules of the C language, I will produce a predictable, working program."

However, if you break a rule labeled as Undefined Behavior, the contract is void. The compiler no longer owes you anything. It doesn't have to crash; it doesn't even have to tell you that you did something wrong.

The "Anything Can Happen" Rule

When the compiler encounters UB, it assumes that code is impossible or won't happen. Because the compiler is obsessed with speed, it won't add safety checks for things it assumes you won't do.

If you trigger UB, the outcome is literally anything:

  1. The "Lucky" Result: The program works fine today, but crashes tomorrow.
  2. The Time Bomb: A variable in a completely different part of your program changes value mysteriously.
  3. The Optimization Trap: The compiler sees code that would cause UB and simply deletes it, changing your program's logic entirely.

A Classic Example: Signed Overflow

In C, if you add 1 to the maximum possible value of a signed integer, the result is undefined. The compiler is allowed to assume you will never let an integer get that high.

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

int main() {
    int x = INT_MAX;
    
    // This is Undefined Behavior
    // It might wrap around to a negative number,
    // it might stay positive, or the program might vanish.
    int y = x + 1;
    
    printf("Result: %d\n", y);
    return 0;
}

Because the behavior is undefined, the compiler might "optimize" your code by assuming x + 1 is always greater than x. If you later write a check like if (x + 1 > x), the compiler might delete the entire if statement because, according to the "contract," x + 1 can never overflow.

Key takeaway

Undefined Behavior means the C standard places no requirements on what the program does; it can crash, produce garbage data, or appear to work perfectly until it fails at the worst possible moment.