Skip to content

Last updated:2026-10-12

C++ assert

About the Author

WeChat official account:

wechat

1. A First assert Example

assert is a macro, not a function.

The assert macro's prototype is defined in (C) and (C++). Its effect is: if its condition returns an error, program execution is terminated.

assert can be disabled by defining NDEBUG, but this must be done at the beginning of the source code, before include .

void assert(int expression);

Code example: assert.c

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

int main() 
{ 
    int x = 7; 

    /*  Some big code in between and let's say x  
    is accidentally changed to 9  */
    x = 9; 

    // Programmer assumes x to be 7 in rest of the code 
    assert(x==7); 

    /* Rest of the code */

    return 0; 
} 
Output:
assert: assert.c:13: main: Assertion 'x==7' failed.
As you can see, the output reveals the source file, the line number, and the location of the error!

2. Assertions vs. Normal Error Handling

  • Assertions are mainly used to check for situations that are logically impossible.

For example, they can be used to check the state the code expects before it starts running, or to check the state after running completes. Unlike normal error handling, assertions are usually disabled at run time.

  • To ignore assertions, add the following at the beginning of the code:
    #define NDEBUG          // 加上这行,则 assert 不可用
    

Code example: ignore_assert.c

Comments