...
Static assertions take the form":
Code Block |
---|
static_assert(constant-expression, string-literal); |
...
While not yet available in C, this behavior can be mimicked as follows:
Code Block |
---|
#define staticcompile_time_assert(constant-expression, string-literale) \ dotypedef { typedef int a[(constant-expressionchar JOIN(assert_, __LINE__) [(e) ? 1 : -1]; } while(0) int main(void) { static_assert(sizeof(int) <= sizeof(long), "sizeof(int) <= sizeof(long)"); /* Passes */ static_assert(sizeof(double) <= sizeof(int), "sizeof(double) <= sizeof(int)"); /* Fails */ } |
Wiki Markup |
---|
The ## operator \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] can be used to concatenate tokens. |
The macro argument string-literal
is ignored in this case, this is meant for future compatibility.
Non-Compliant Code Example
This non-compliant code example ...code uses the assert()
macro to assert a property concerning a memory-mapped structure that is essential for the code that uses this structure to behave correctly.
Code Block | ||
---|---|---|
| ||
struct timer {
uint8_t MODE;
uint32_t DATA;
uint32_t COUNT;
};
int main(void) {
assert(offsetof(timer, DATA) == 4);
}
|
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.
Non-Compliant Code Example
For assertions involving only constant expressions, some C++ compilers let you use a preprocessor conditional statement, as in:
Code Block | ||
---|---|---|
| ||
#if (offsetof(timer, DATA) != 4)
#error DATA must be at offset 4
#endif
|
C99 does not recognize sizeof
, offsetof
and enumeration constants in #if
conditions. Some compilers allow these constructs in conditionals as an extension, but most do not.
Compliant Solution
This compliant solution ...
...
Wiki Markup |
---|
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section ???6.10.3.3, "NameThe ## operator" [Klarer 04] R. Klarer, J. Maddock, B. Dawes, and H. Hinnant. "Proposal to Add Static Assertions to the Core Language (Revision 3)" (ISO C++ committee paper ISO/IEC JTC1/SC22/WG21/N1720, October 2004). This document is available online at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1720.html. \[Saks 08] Dan Saks, Stephen C. Dewhurst. Presentation. Sooner Rather Than Later: Static Programming Techniques for C++. \[Saks 05] Dan Saks. [_Catching errors early with compile-time assertions|http://www.embedded.com/columns/programmingpointers/164900888?_requestid=287187]. Embedded Systems Design. June, 2005. \[Eckel 2007] Bruce Eckel. [_Thinking in C++ - Volume 2_|http://bruce-eckel.developpez.com/livres/cpp/ticpp/v2/]. January 25, 2007. |
...
DCL02-A. Use visually distinct identifiers 02. Declarations and Initialization (DCL) DCL04-A. Take care when declaring more than one variable per declaration