Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
/* Passes */
static_assert(
  sizeof(int) &lt;<= sizeof(void*), 
  &quot;"sizeof(int) &lt;<= sizeof(void*)&quot;"
); 

/* Fails */
static_assert(
  sizeof(double) &lt;<= sizeof(int), 
  &quot;"sizeof(double) &lt;<= sizeof(int)&quot;"
);

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
bgColor#ccccff
struct timer {
  uint8_t MODE;
  uint32_t DATA;
  uint32_t COUNT;
};

#if (offsetof(timer, DATA) != 4)
  #error &quot;"DATA must be at offset 4&quot;"
#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, &quot;"Conditional inclusion,&quot;" and Section 6.10.3.3, &quot;"The ## operator,&quot;" and Section 7.2.1, &quot;"Program diagnostics&quot;"
\[[Klarer 04|AA. C References#Klarer 04]\]
\[[Saks 05|AA. C References#Saks 05]\]
\[[Saks 08|AA. C References#Saks 08]\]

...

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;        02. Declarations and Initialization (DCL)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;