Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/language/static assert"

From cppreference.com
< cpp‎ | language
m (+References)
 
(8 intermediate revisions by 5 users not shown)
Line 1: Line 1:
 
{{title|{{tt|static_assert}} declaration {{mark since c++11}}}}
 
{{title|{{tt|static_assert}} declaration {{mark since c++11}}}}
 
{{cpp/language/declarations/navbar}}
 
{{cpp/language/declarations/navbar}}
 +
 
Performs compile-time assertion checking.
 
Performs compile-time assertion checking.
  
 
===Syntax===
 
===Syntax===
 
{{sdsc begin}}
 
{{sdsc begin}}
{{sdsc|notes={{mark since c++11}}|{{ttb|static_assert(}} {{spar|bool-constexpr}} {{ttb|,}} {{spar|message}} {{ttb|)}}}}  
+
{{sdsc|num=1|
{{sdsc|notes={{mark since c++17}}|{{ttb|static_assert(}} {{spar|bool-constexpr}} {{ttb|)}}}}
+
{{ttb|static_assert(}} {{spar|bool-constexpr}} {{ttb|,}} {{spar|unevaluated-string}} {{ttb|)}}
 +
}}
 +
{{sdsc|num=2|notes={{mark since c++17}}|
 +
{{ttb|static_assert(}} {{spar|bool-constexpr}} {{ttb|)}}
 +
}}
 +
{{sdsc|num=3|notes={{mark since c++26}}|
 +
{{ttb|static_assert(}} {{spar|bool-constexpr}} {{ttb|,}} {{spar|constant-expression}} {{ttb|)}}
 +
}}
 
{{sdsc end}}
 
{{sdsc end}}
 +
 +
Declares a static assertion. If the assertion fails, the program is ill-formed, and a diagnostic error message may be generated.
 +
@1@ A static assertion with fixed error message.
 +
@2@ A static assertion without error message.
 +
@3@ A static assertion with user-generated error message.
 +
@@ This syntax can only be matched if syntax {{v|1}} does not match.
  
 
===Explanation===
 
===Explanation===
Line 15: Line 29:
 
|since2=c++23|rev2=an expression {{rlp|implicit conversion#Contextual conversions|contextually converted to {{c/core|bool}}}} where the conversion is a {{rlp|constant expression}}
 
|since2=c++23|rev2=an expression {{rlp|implicit conversion#Contextual conversions|contextually converted to {{c/core|bool}}}} where the conversion is a {{rlp|constant expression}}
 
}}}}
 
}}}}
{{par|{{spar|message}}|
+
{{par|{{spar|unevaluated-string}}|an {{rlp|string literal#Unevaluated strings|unevaluated string literal}} that will appear as the error message}}
* {{rev inl|since=c++17|optional }} string literal that will appear as compiler error if {{spar|bool-constexpr}} is false{{rev inl|until=c++23|, except that characters not in the {{rlp|charset#Basic character set|basic character set}} are not required to appear}}
+
{{par|{{spar|constant-expression}}|a {{rlp|constant expression}} {{c|msg}} satisfying all following conditions:
{{rrev|since=c++26|
+
* {{c|msg.size()}} is implicitly convertible to {{lc|std::size_t}}.
* or an expression {{c|msg}} such that
+
* {{c|msg.data()}} is implicitly convertible to {{c/core|const char*}}.}}
** {{c|msg.size()}} is implicitly convertible to {{c|std::size_t}}
+
** {{c|msg.data()}} is implicitly convertible to {{c|const char*}}
+
}}}}
+
 
{{par end}}
 
{{par end}}
  
A {{tt|static_assert}} declaration may appear at namespace and block scope (as a {{rlp|declarations|block declaration}}) and inside a class body (as a {{rlp|class|member declaration}}).
+
A {{c/core|static_assert}} declaration may appear at namespace and block {{rlp|scope}} (as a {{rlp|declarations|block declaration}}) and inside a class body (as a {{rlp|class|member declaration}}).
  
If {{spar|bool-constexpr}} is well-formed and evaluates to {{c|true}}, or is evaluated in the context of a template definition and the template is uninstantiated, this declaration has no effect. Otherwise a compile-time error is issued, and the text of {{spar|message}}, if any, is included in the diagnostic message.
+
If {{spar|bool-constexpr}} is well-formed and evaluates to {{c|true}}, or is evaluated in the context of a template definition and the template is uninstantiated, this declaration has no effect. Otherwise a compile-time error is issued, and the user-provided message, if any, is included in the diagnostic message.
  
 +
The text of the user-provided message is determined as follows:
 +
* If the message matches the syntactic requirements of {{spar|unevaluated-string}}, the text of the message is the text of the {{spar|unevaluated-string}}.
 
{{rrev|since=c++26|
 
{{rrev|since=c++26|
If {{spar|message}} is not a string literal, it is evaluated only if {{spar|bool-constexpr}} evaluates to {{c|false}}. The text of {{spar|message}} is formed by the character sequence {{range|msg.data()|msg.data() + msg.size()}} which must denote a valid range, and each element in the sequence must be an integral constant expression.
+
* Otherwise, given the following values:
 +
:* Let {{c|msg}} denote the value of {{spar|constant-expression}}.
 +
:* Let {{c|len}} denote the value of {{c|msg.size()}}, which must be a {{rlpsd|constant expression#Converted constant expression}} of type {{lc|std::size_t}}.
 +
:* Let {{c|ptr}} denote the expression {{c|msg.data()}}, {{rlp|implicit conversion|implicitly converted}} to {{c/core|const char*}}. {{c|ptr}} must be a {{rlpsd|constant expression#Core constant expression}}.
 +
: The text of the message is formed by the sequence of {{c|len}} {{rlp|charset#Code unit and literal encoding|code units}}, starting at {{c|ptr}}, of the {{rlp|charset#Code unit and literal encoding|ordinary literal encoding}}. For each integer {{c|i}} in {{range|0|len}}, {{c|ptr[i]}} must be an {{rlpsd|constant expression#Integral constant expression}}.
 
}}
 
}}
  
 
===Notes===
 
===Notes===
 +
The standard does not require a compiler to print the verbatim text of {{spar|message}}, though compilers generally do so as much as possible.
 +
 
{{rrev|until=c++26|
 
{{rrev|until=c++26|
 
Since {{spar|message}} has to be a string literal, it cannot contain dynamic information or even a {{rlp|constant expression}} that is not a string literal itself. In particular, it cannot contain the {{rlp|name}} of the {{rlp|template parameters|template type argument}}.
 
Since {{spar|message}} has to be a string literal, it cannot contain dynamic information or even a {{rlp|constant expression}} that is not a string literal itself. In particular, it cannot contain the {{rlp|name}} of the {{rlp|template parameters|template type argument}}.
 
}}
 
}}
 
{{ftm begin|core=1|std=1|comment=1}}
 
{{ftm begin|core=1|std=1|comment=1}}
{{ftm|value=200410L|std=C++11|__cpp_static_assert|rowspan="3"|{{box|{{c/core|static_assert(}}{{spar sep|bool-constexpr}}{{c/core|, "comment")}}}}}}
+
{{ftm|value=200410L|std=C++11|__cpp_static_assert|rowspan="3"|{{c/core|static_assert}} (syntax {{v|1}})}}
{{ftm|value=201411L|std=C++17|-|Single-argument {{box|{{c/core|static_assert(}}{{spar sep|bool-constexpr}}{{c/core|)}}}}}}
+
{{ftm|value=201411L|std=C++17|-|Single-argument {{c/core|static_assert}} (syntax {{v|2}})}}
{{ftm|value=202306L|std=C++26|-|user-generated static_assert messages}}
+
{{ftm|value=202306L|std=C++26|-|user-generated error messages (syntax {{v|3}}}}
 
{{ftm end}}
 
{{ftm end}}
 +
 +
===Keywords===
 +
{{ltt|cpp/keyword/static_assert}}
  
 
===Example===
 
===Example===
 
{{example
 
{{example
 
|code=
 
|code=
 +
#include <format>
 
#include <type_traits>
 
#include <type_traits>
  
Line 89: Line 112:
 
     no_default() = delete;
 
     no_default() = delete;
 
};
 
};
 +
 +
#if __cpp_static_assert >= 202306L
 +
// Not real C++ yet (std::format should be constexpr to work):
 +
static_assert(sizeof(int) == 4, std::format("Expected 4, got {}", sizeof(int)));
 +
#endif
  
 
int main()
 
int main()
Line 105: Line 133:
 
1: error: static assertion failed: Swap requires copying
 
1: error: static assertion failed: Swap requires copying
 
2: error: static assertion failed: Data structure requires default-constructible elements
 
2: error: static assertion failed: Data structure requires default-constructible elements
 +
3: error: static assertion failed: Expected 4, got 2
 
}}
 
}}
  
Line 110: Line 139:
 
{{dr list begin}}
 
{{dr list begin}}
 
{{dr list item|wg=cwg|dr=2039|std=C++11|before=only the expression before conversion is required to be constant|after=the conversion must also be<br>valid in a constant expression}}
 
{{dr list item|wg=cwg|dr=2039|std=C++11|before=only the expression before conversion is required to be constant|after=the conversion must also be<br>valid in a constant expression}}
{{dr list item|wg=cwg|dr=2518<!-- P2593R1 -->|std=C++11|before=uninstantiated {{c|static_assert(false, "");}} was error|after=made well-formed}}
+
{{dr list item|wg=cwg|dr=2518|paper=P2593R1|std=C++11|before=uninstantiated {{c|static_assert(false, "");}} was ill-formed|after=made well-formed}}
 
{{dr list end}}
 
{{dr list end}}
 +
 +
===References===
 +
{{ref std c++23}}
 +
{{ref std|section=9.1|title=Preamble|id=dcl.pre|p=10}}
 +
{{ref std end}}
 +
{{ref std c++20}}
 +
{{ref std|section=9.1|title=Preamble|id=dcl.pre|p=6}}
 +
{{ref std end}}
 +
{{ref std c++17}}
 +
{{ref std|section=10|title=Declarations|id=dcl.dcl|p=6}}
 +
{{ref std end}}
 +
{{ref std c++14}}
 +
{{ref std|section=7|title=Declarations|id=dcl.dcl|p=4}}
 +
{{ref std end}}
 +
{{ref std c++11}}
 +
{{ref std|section=7|title=Declarations|id=dcl.dcl|p=4}}
 +
{{ref std end}}
  
 
===See also===
 
===See also===
Line 118: Line 164:
 
{{dsc inc|cpp/error/dsc assert}}
 
{{dsc inc|cpp/error/dsc assert}}
 
{{dsc inc|cpp/types/dsc enable_if}}
 
{{dsc inc|cpp/types/dsc enable_if}}
{{dsc|[[cpp/types#Type_traits_.28since_C.2B.2B11.29|'''Type traits''']] {{mark c++11}}|defines a compile-time template-based interface to query or modify the properties of types|nomono=true}}
+
{{dsc|[[cpp/meta#Type_traits|'''Type traits''']] {{mark c++11}}|define compile-time template-based interfaces to query the properties of types|nomono=true}}
 
{{dsc see c|c/language/_Static_assert|Static assertion|nomono=true}}
 
{{dsc see c|c/language/_Static_assert|Static assertion|nomono=true}}
 
{{dsc end}}
 
{{dsc end}}
  
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}

Latest revision as of 01:46, 14 August 2024

 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 
 

Performs compile-time assertion checking.

Contents

[edit] Syntax

static_assert( bool-constexpr , unevaluated-string ) (1)
static_assert( bool-constexpr ) (2) (since C++17)
static_assert( bool-constexpr , constant-expression ) (3) (since C++26)

Declares a static assertion. If the assertion fails, the program is ill-formed, and a diagnostic error message may be generated.

1) A static assertion with fixed error message.
2) A static assertion without error message.
3) A static assertion with user-generated error message.
This syntax can only be matched if syntax (1) does not match.

[edit] Explanation

bool-constexpr -

a contextually converted constant expression of type bool. Built-in conversions are not allowed, except for non-narrowing integral conversions to bool.

(until C++23)

an expression contextually converted to bool where the conversion is a constant expression

(since C++23)
unevaluated-string - an unevaluated string literal that will appear as the error message
constant-expression - a constant expression msg satisfying all following conditions:
  • msg.size() is implicitly convertible to std::size_t.
  • msg.data() is implicitly convertible to const char*.

A static_assert declaration may appear at namespace and block scope (as a block declaration) and inside a class body (as a member declaration).

If bool-constexpr is well-formed and evaluates to true, or is evaluated in the context of a template definition and the template is uninstantiated, this declaration has no effect. Otherwise a compile-time error is issued, and the user-provided message, if any, is included in the diagnostic message.

The text of the user-provided message is determined as follows:

  • If the message matches the syntactic requirements of unevaluated-string, the text of the message is the text of the unevaluated-string.
  • Otherwise, given the following values:
The text of the message is formed by the sequence of len code units, starting at ptr, of the ordinary literal encoding. For each integer i in [0len), ptr[i] must be an integral constant expression.
(since C++26)

[edit] Notes

The standard does not require a compiler to print the verbatim text of message, though compilers generally do so as much as possible.

Since message has to be a string literal, it cannot contain dynamic information or even a constant expression that is not a string literal itself. In particular, it cannot contain the name of the template type argument.

(until C++26)
Feature-test macro Value Std Feature
__cpp_static_assert 200410L (C++11) static_assert (syntax (1))
201411L (C++17) Single-argument static_assert (syntax (2))
202306L (C++26) user-generated error messages (syntax (3)

[edit] Keywords

static_assert

[edit] Example

#include <format>
#include <type_traits>
 
static_assert(03301 == 1729); // since C++17 the message string is optional
 
template<class T>
void swap(T& a, T& b) noexcept
{
    static_assert(std::is_copy_constructible_v<T>,
                  "Swap requires copying");
    static_assert(std::is_nothrow_copy_constructible_v<T> &&
                  std::is_nothrow_copy_assignable_v<T>,
                  "Swap requires nothrow copy/assign");
    auto c = b;
    b = a;
    a = c;
}
 
template<class T>
struct data_structure
{
    static_assert(std::is_default_constructible_v<T>,
                  "Data structure requires default-constructible elements");
};
 
template<class>
constexpr bool dependent_false = false; // workaround before CWG2518/P2593R1
 
template<class T>
struct bad_type
{
    static_assert(dependent_false<T>, "error on instantiation, workaround");
    static_assert(false, "error on instantiation"); // OK because of CWG2518/P2593R1
};
 
struct no_copy
{
    no_copy(const no_copy&) = delete;
    no_copy() = default;
};
 
struct no_default
{
    no_default() = delete;
};
 
#if __cpp_static_assert >= 202306L
// Not real C++ yet (std::format should be constexpr to work):
static_assert(sizeof(int) == 4, std::format("Expected 4, got {}", sizeof(int)));
#endif
 
int main()
{
    int a, b;
    swap(a, b);
 
    no_copy nc_a, nc_b;
    swap(nc_a, nc_b); // 1
 
    [[maybe_unused]] data_structure<int> ds_ok;
    [[maybe_unused]] data_structure<no_default> ds_error; // 2
}

Possible output:

1: error: static assertion failed: Swap requires copying
2: error: static assertion failed: Data structure requires default-constructible elements
3: error: static assertion failed: Expected 4, got 2

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
CWG 2039 C++11 only the expression before conversion is required to be constant the conversion must also be
valid in a constant expression
CWG 2518
(P2593R1)
C++11 uninstantiated static_assert(false, ""); was ill-formed made well-formed

[edit] References

  • C++23 standard (ISO/IEC 14882:2024):
  • 9.1 Preamble [dcl.pre] (p: 10)
  • C++20 standard (ISO/IEC 14882:2020):
  • 9.1 Preamble [dcl.pre] (p: 6)
  • C++17 standard (ISO/IEC 14882:2017):
  • 10 Declarations [dcl.dcl] (p: 6)
  • C++14 standard (ISO/IEC 14882:2014):
  • 7 Declarations [dcl.dcl] (p: 4)
  • C++11 standard (ISO/IEC 14882:2011):
  • 7 Declarations [dcl.dcl] (p: 4)

[edit] See also

shows the given error message and renders the program ill-formed
(preprocessing directive)[edit]
aborts the program if the user-specified condition is not true. May be disabled for release builds.
(function macro) [edit]
(C++11)
conditionally removes a function overload or template specialization from overload resolution
(class template) [edit]
Type traits (C++11) define compile-time template-based interfaces to query the properties of types
C documentation for Static assertion