W3cubDocs

/C

Static assertion

Syntax

_Static_assert ( expression , message ) (since C11)
_Static_assert ( expression ) (since C23)
expression - any integer constant expression
message - any string literal

This keyword is also available as convenience macro static_assert, available in the header <assert.h>.

Explanation

The constant expression is evaluated at compile time and compared to zero. If it compares equal to zero, a compile-time error occurs and the compiler must display message (if provided) as part of the error message (except that characters not in basic source character set aren't required to be displayed).

Otherwise, if expression does not equal zero, nothing happens; no code is emitted.

Keywords

_Static_assert.

Example

#include <assert.h>
int main(void)
{
    // Test if math works.
    static_assert(2 + 2 == 4, "Whoa dude!"); // or _Static_assert(...
 
    // This will produce an error at compile time.
    static_assert(sizeof(int) < sizeof(char),
                 "this program requires that int is less than char");
}

References

  • C17 standard (ISO/IEC 9899:2018):
    • 6.7.10 Static assertions (p: 105)
    • 7.2 Diagnostics <assert.h> (p: 135)
  • C11 standard (ISO/IEC 9899:2011):
    • 6.7.10 Static assertions (p: 145)
    • 7.2 Diagnostics <assert.h> (p: 186-187)

See also

aborts the program if the user-specified condition is not true. May be disabled for release builds
(function macro)
C++ documentation for static_assert declaration

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/c/language/static_assert