...
While the use of the runtime assertion is better than nothing, it needs to be placed in a function and executed, typically removed from the actual structure to which it refers. The diagnostic only occurs at runtime, and only if the code path containing the assertion is executed.
...
Compliant
...
Solution
For assertions involving only constant expressions, some implementations allow the use a preprocessor conditional statement, as in:
Code Block | ||
---|---|---|
| ||
struct timer { uint8_t MODE; uint32_t DATA; uint32_t COUNT; }; #if (offsetof(timer, DATA) != 4) #error DATA must be at offset 4 #endif |
Using #error
directives allows for clear diagnostic messages. Because this approach evaluates assertions at compile time, there is no run-time penalty.
Unfortunately, this solution is not portable. C99 does not recognize require that implementations support sizeof
, offsetof
and or enumeration constants in #if
conditions (see C99, . According to Section 6.10.1, "Conditional inclusion"), all identifiers in the expression that controls conditional inclusion either are, or are not, macro names. Some compilers allow these constructs in conditionals as an extension, but most do not.
Compliant Solution
This compliant solution mimics the behavior of static_assert
in a portable manner.
...