Assertions are a valuable diagnostic tool for finding and eliminating software defects that may result in vulnerabilities (see MSC11-A. Incorporate diagnostic tests using assertions). The runtime assert()
macro has some limitations, however, in that it occurs incurs a runtime overhead and, because it calls abort()
, is only useful for identifying incorrect assumptions and is not intended for runtime error checking. Consequently, runtime assertions are generally unsuitable for server programs or embedded systems.
...
According to the C++ 0X draft standard, the constant-expression
in a static assert declaration is a constant expression that can be converted to bool
at compile time. If the value of the converted expression is true, the declaration has no effect. Otherwise the program is ill-formed, and a diagnostic message (which includes the text of the string-literal
) is issued at compile time. For example:
Code Block |
---|
/* Passes */ static_assert( sizeof(int) <= sizeof(void*), "sizeof(int) <= sizeof(void*)" ); /* Fails */ static_assert( sizeof(double) <= sizeof(int), "sizeof(double) <= sizeof(int)" ); |
...
The static_assert()
macro accepts a constant expression e
, which is evaluated as the first operand to the conditional operator. If e
evaluates to nonzero, an array type with a dimension of 1 is defined; otherwise, an array type with a dimension of -1 is defined. Because it is invalid to declare an array with a negative dimension, the resulting type definition will be flagged by the compiler. The name of the array is used to indicate the location of the failed assertion.
...
Static assertions allow incorrect assumptions to be diagnosed at compile time, instead of resulting in a silent malfunction or runtime error. Because the assertion is performed at compile time, no runtime cost in space or time is incurred. An assertion can be used at file or block scope, and failure results in a meaningful and informative diagnostic error message.
...