Learn++ Lesson 43: Static_assert in C++ Programming

static_assert checks a condition during compilation. If the condition is false, the compiler reports an error before the program can run.

Check a type size at compile time

#include <iostream>
static_assert(sizeof(int) == 4, "Int size is not 4 bytes");
int main() {
    std::cout << "Something...";
    return 0;
}

Output:

Something...

The assertion verifies that sizeof(int) is exactly 4 bytes. When the condition is true, compilation continues and the program runs normally; when it is false, compilation stops with the supplied message.

Why static_assert matters

  • It catches invalid assumptions before runtime.
  • It can enforce type sizes, constant values, and template constraints.
  • It documents compile-time requirements close to the code they protect.

What you practice in the app

  • Writing a static_assert condition.
  • Using sizeof(int) in a compile-time check.
  • Recognizing that a failed assertion prevents compilation.

Today's challenge

Fill in the missing number so the assertion succeeds and the program prints Something...:

#include <iostream>
static_assert(sizeof(int) == _____, "Int size is not 4 bytes");
int main() {
    std::cout << "Something...";
    return 0;
}

The unique answer on the target compiler is 4, because sizeof(int) evaluates to 4.