This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 22.3.1 - The assert macro shall not be used with a constant-expression
[dcl.dcl]
Category: Required
Analysis: Decidable,Single Translation Unit
Rationale
There are a number of limitations to consider when using the assert macro. For example:
- An
assert failure is only reported at run-time, requiring that a failure also has to be managed at run-time;
- The
assert macro can only be used in contexts where an expression is allowed;
- The
assert macro may be disabled at build-time.
It is better to use static_assert when the condition being asserted is a constant-expression, as this ensures that any
failure will be detected at compile time.
Exception
assert( false ) or assert( false && "any string literal" ) may be used to identify paths that are not expected to
be executed.
Example
static_assert( ( sizeof( int ) == 4 ), "Bad size" ); // Rule does not apply
void f( int32_t i )
{
assert( i < 1000 ); // Compliant - not constant
if ( i >= 0 )
{
assert( ( sizeof( int ) == 4 ) && "Bad size" ); // Non-compliant - constant
}
else
{
assert( false && "i is negative" ); // Compliant by exception
}
}
Copyright The MISRA Consortium Limited © 2023