Assertion
suggest changeIntroduction
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
Parameter | Details |
——— | —–– |
expression | expression of scalar type. |
message | string 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
callsabort
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 ordinaryif/else
conditions andexit
orquick_exit
to end the program. In contrast toabort
, these allow the program to do some cleanup (via functions registered withatexit
orat_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.