...
Code Block |
---|
/* Passes */ static_assert( sizeof(int) <<= sizeof(void*), ""sizeof(int) <<= sizeof(void*)"" ); /* Fails */ static_assert( sizeof(double) <<= sizeof(int), ""sizeof(double) <<= sizeof(int)"" ); |
Static assertion is not available in C99, but the facility is being considered for inclusion in C1X by the ISO/IEC WG14 international standardization working group.
...
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 runtime penalty.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C++ Secure Coding Standard as DCL03-CPP. Use a static assertion to test the value of a constant expression.
References
Wiki Markup |
---|
\[[Becker 08|AA. C References#Becker 08]\] \[[Eckel 07|AA. C References#Eckel 07]\] \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.10.1, ""Conditional inclusion,"" and Section 6.10.3.3, ""The ## operator,"" and Section 7.2.1, ""Program diagnostics"" \[[Klarer 04|AA. C References#Klarer 04]\] \[[Saks 05|AA. C References#Saks 05]\] \[[Saks 08|AA. C References#Saks 08]\] |
...
02. Declarations and Initialization (DCL)