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.
Parameter | Details |
——— | —–– |
expression | expression of scalar type. |
message | string 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)#else# define assert(condition) /* implementation defined */#endif
Opinion varies about whether NDEBUG should always be used for production compilations.
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).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.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.