Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      Static assertion(since C11)

      From cppreference.com
      <c‎ |language
       
       
       
       

      Contents

      [edit]Syntax

      _Static_assert(expression,message)(since C11)(deprecated in C23)
      static_assert(expression,message)(since C23)
      _Static_assert(expression)(since C23)(deprecated in C23)
      static_assert(expression)(since C23)
      expression - anyinteger constant expression
      message - anystring literal

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

      (until C23)

      Both ofstatic_assert and_Static_assert have the same effects._Static_assert is a deprecated spelling that is kept for compatibility.

      An implementation may also definestatic_assert and/or_Static_assert as predefined macros, andstatic_assert is no longer provided by<assert.h>.

      (since C23)

      [edit]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 compilermust displaymessage as part of the error message (except that characters not inbasic character set are not required to be displayed)(until C23)should displaymessage (if provided) as part of the error message(since C23).

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

      [edit]Keywords

      _Static_assert,static_assert

      [edit]Example

      Run this code
      #include <assert.h> // no longer needed since C23 int main(void){// Test if math works, C23:    static_assert((2+2)%3==1,"Whoa dude, you knew!");// Pre-C23 alternative:    _Static_assert(2+2*2==6,"Lucky guess!?"); // This will produce an error at compile time.// static_assert(sizeof(int) < sizeof(char), "Unmet condition!");     constexprint _42=2*3*2*3+2*3;    static_assert(_42==42);// the message string can be omitted. // const int _13 = 13;// Compile time error - not an integer constant expression:// static_assert(_13 == 13);}

      [edit]References

      • C23 standard (ISO/IEC 9899:2024):
      • 6.7.11 Static assertions (p: TBD)
      • 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)

      [edit]See also

      aborts the program if the user-specified condition is nottrue. May be disabled for release builds
      (function macro)[edit]
      C++ documentation forstatic_assert declaration
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=c/language/_Static_assert&oldid=180000"

      [8]ページ先頭

      ©2009-2025 Movatter.jp