Course contentsShow
← C
Lesson 901 of 1,21912. The Standard LibraryFree lesson

Using `assert` for internal debugging

Using assert for internal debugging

What you'll learn: How to use the assert() macro to catch logical errors during development by setting "tripwires" in your code.

The coding "tripwire"

Imagine you are building a bridge. You are certain that the steel cables you ordered are exactly 10 meters long. If a cable arrives and it is only 5 meters long, the bridge will collapse later. Instead of waiting for the disaster, you place a sensor at the gate: if a cable isn't 10 meters, the whole construction site shuts down immediately so you can fix the order.

In C, assert() is that sensor. It is a macro provided by the <assert.h> header that tests a condition. If the condition is true, nothing happens. If it is false, your program prints an error message and terminates instantly.

How to use assert

You use assert to check for things that should never happen if your logic is correct. It is not for handling user errors (like a typo in a password); it is for catching your own programming mistakes (like passing a NULL pointer to a function that requires data).

#include <stdio.h>
#include <assert.h>

void process_age(int age) {
    // A person's age should never be negative. 
    // If it is, there is a bug in the code that calls this function.
    assert(age >= 0);

    printf("Processing age: %d\n", age);
}

int main() {
    process_age(25);  // Works fine
    process_age(-5);  // The program will crash here with a helpful message
    
    return 0;
}

When process_age(-5) runs, the program stops and tells you exactly which file and which line failed. This prevents the "garbage in, garbage out" problem where a small mistake early on turns into a massive, hard-to-trace bug later.

Turning it off

The best part about assert is that it is for development. When you are ready to ship your software to users, you can disable all asserts at once by defining NDEBUG before including the header. This means your final app runs at full speed without the extra checks, but during the "building" phase, you have a safety net protecting every step.

Key takeaway

Use assert() to verify internal logic assumptions; it halts the program immediately if a condition fails, making bugs easy to find during development.