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

Disabling assertions with `NDEBUG`

Disabling assertions with NDEBUG

What you'll learn: How to instantly turn off all assert() checks in your program to improve performance for final release.

Training wheels for code

Think of assert() statements like the training wheels on a bicycle. When you are learning to ride (or in our case, developing code), they are essential. They catch you before you fall by crashing the program if a logic error occurs. However, once you are a professional cyclist entering a race, those training wheels become a burden—they add weight and slow you down.

In C programming, assertions take a small amount of CPU time to check conditions. In a massive program with thousands of checks, this can noticeably impact speed. When your code is finished and tested, you want to "remove the training wheels" for the final version sent to users.

The NDEBUG switch

Instead of manually deleting every assert() line from your source code—which would be a nightmare to put back later if you found a bug—the C Standard Library provides a "kill switch" called NDEBUG (which stands for "No Debug").

When the compiler sees that NDEBUG is defined, it tells the preprocessor to ignore all assert() calls. They stay in your text file, but they vanish from the final machine code, resulting in a smaller, faster program.

How to use it

You must define NDEBUG before including <assert.h>. If you include the header first, the switch won't work.

#include <stdio.h>

// 1. Define NDEBUG to disable all assertions
#define NDEBUG
#include <assert.h>

int main() {
    int speed = 150;

    // This check would normally crash the program because 150 > 100.
    // Because NDEBUG is defined, this line is completely ignored.
    assert(speed <= 100);

    printf("Program continued despite the failed assertion.\n");
    return 0;
}

Professional tip: Compiler flags

In real-world projects, programmers rarely type #define NDEBUG directly into their C files. Instead, they leave the code alone and tell the compiler to add the definition during the build process. If you are using a tool like GCC, you can add the flag -DNDEBUG to your build command. This allows you to create a "Debug" version (with assertions) and a "Release" version (without them) from the exact same source code.

Key takeaway

Defining NDEBUG before including <assert.h> disables all assertions, allowing your final production code to run at maximum speed without safety checks.