C Language Assertion

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


An assertion is a predicate that the presented condition must be true at the moment the assertion is encountered by the software. Most common are simple assertions, which are validated at execution time. However, static assertions are checked at compile time.


  • assert(expression)
  • static_assert(expression, message)
  • _Static_assert(expression, message)


expressionexpression of scalar type.
messagestring literal to be included in the diagnostic message.


Both assert and static_assert are macros defined in assert.h.

The definition of assert depends on the macro NDEBUG which is not defined by the standard library. If NDEBUG is defined, assert is a no-op:

#ifdef NDEBUG
#  define assert(condition) ((void) 0)
#  define assert(condition) /* implementation defined */

Opinion varies about whether NDEBUG should always be used for production compilations.

  • The pro-camp argues that assert calls abort and assertion messages are not helpful for end users, so the result is not helpful to user. If you have fatal conditions to check in production code you should use ordinary if/else conditions and exit or quick_exit to end the program. In contrast to abort, these allow the program to do some cleanup (via functions registered with atexit or at_quick_exit).
  • The con-camp argues that assert calls should never fire in production code, but if they do, the condition that is checked means there is something dramatically wrong and the program will misbehave worse if execution continues. Therefore, it is better to have the assertions active in production code because if they fire, hell has already broken loose.
  • Another option is to use a home-brew system of assertions which always perform the check but handle errors differently between development (where abort is appropriate) and production (where an 'unexpected internal error - please contact Technical Support' may be more appropriate).

static_assert expands to _Static_assert which is a keyword. The condition is checked at compile time, thus condition must be a constant expression. There is no need for this to be handled differently between development and production.

Got any C Language Question?