CodeBlanks Logo Icon CodeBlanks

static_assert

Learn compile-time checks with static_assert.

static_assert

static_assert is a construct that checks a condition at compile time. If the condition is false, compilation stops and a message is shown.

Example: static_assert(sizeof(int) == 4, "int must be 4 bytes");. If the condition is true, nothing happens; the code compiles. This is used to verify template parameters and type traits during compilation. The runtime cost is zero, because the check happens only at compile time. Since C++17 the message is optional.

static_assert and templates

static_assert is often used in template code. It can verify at compile time that a template parameter meets certain traits.

For example, static_assert(sizeof(T) >= 4, "T must be at least 4 bytes"); checks the size of type T. This catches at compile time errors that would otherwise surface at runtime. When the template is called with the type the developer expects, compilation succeeds; if a wrong type is given, a clear error message is shown.

Practice Check type size with static_assert

Inside main write static_assert(sizeof(int) >= 2, "int at least 2 bytes");. Then print "OK" with std::cout to show compilation succeeded.

Starter code

main.cpp
#include <iostream>

int main() {
    // Add static_assert and a message
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    static_assert(sizeof(int) >= 2, "int at least 2 bytes");
    std::cout << "OK";
    return 0;
}

Expected output

OK

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its meaning

Term Meaning
static_assert Compile-time check
sizeof(int) Type size
false Compile error
true Compilation continues

2 What does static_assert(false, ...) do?

main.cpp
static_assert(false, "error");
  • Throws a runtime error
  • Issues a warning
  • Does nothing
  • Stops compilation Correct answer

Explanation: static_assert(false, ...) stops compilation and shows the message.

3 Complete the static_assert condition

Question
static_assert(sizeof(int) >= ____, "int at least 2 bytes");
Answer
static_assert(sizeof(int) >= 2, "int at least 2 bytes");

Explanation: sizeof(int) >= 2 is valid on modern systems.

All lessons in Intermediate