Stats

595 Contributors: 18
2017-03-02
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Assertion

Download c eBook

Introduction

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.

Syntax

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

Parameters

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

Remarks

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)
#else
#  define assert(condition) /* implementation defined */
#endif

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.

Related Examples