Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

static_assert — a compile-time assertion

static_assert checks a constant condition during compilation. A false condition outside the context of a template definition makes the program ill-formed and requires a diagnostic. An optional string literal describes the violated assumption.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

static_assert(condition);
static_assert(condition, "message");

static_assert is a declaration that checks a condition during compilation. After contextual conversion to bool, the condition must be a constant expression. The assertion has no effect if the condition is true or if it is evaluated in the context of a template definition, even if it is false there. Otherwise, a false condition makes the program ill-formed and requires a diagnostic. Thus, static_assert(false); in a template need not be diagnosed if that assertion is never instantiated.

C++23 supports static_assert(condition); and static_assert(condition, "message");. The message is an optional string literal, not text computed at runtime. The declaration ends with a semicolon. It can appear in a class, among other places; there it introduces neither a data member nor a member function.

The example checks that capacity is positive and even. Changing it to 7 violates the second assertion. Do not expect identical diagnostic wording across compilers.

This entry targets C++23. The supplied site publishes an evolving draft, not a frozen C++23 text; newer message extensions are excluded here. A repository compiler flag does not attest to the production environment.

Examples

constexpr int capacity = 8;
static_assert(capacity > 0, "capacity must be positive");
static_assert(capacity % 2 == 0);

int main() {
    return 0;
}

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources