C++ static_assert

The static_assert keyword in C++ is a compile-time assertion that checks conditions during compilation. If the condition is false, the compiler generates an error, halting the build process. This feature is particularly useful for enforcing constraints and validating assumptions in your code without incurring runtime overhead.

Introduced in C++11, static_assert allows developers to write safer and more robust code by catching errors early during compilation rather than at runtime. Starting from C++17, the second parameter (custom error message) is optional.


Syntax

</>
Copy
static_assert(constexpr_condition, "Error message"); // C++11 and later
static_assert(constexpr_condition);                   // C++17 and later
constexpr_condition
A compile-time constant expression that evaluates to true or false.
Error message
A string literal displayed by the compiler if the assertion fails. Optional in C++17 and later.

Examples

Example 1: Basic Use of static_assert

This example demonstrates a simple use case for static_assert to enforce size constraints on a data type.

</>
Copy
#include <iostream>
using namespace std;

int main() {
    static_assert(sizeof(int) == 4, "int size is not 4 bytes"); // Verify size of int
    cout << "All static_assert checks passed!" << endl;
    return 0;
}

Output:

All static_assert checks passed!

Explanation:

  1. The static_assert ensures that sizeof(int) is 4 bytes. If not, the compiler will produce an error with the custom message.
  2. Since the condition evaluates to true on most platforms, the program compiles and runs successfully.

Example 2: Using static_assert in Templates

The static_assert keyword is especially useful in templates to enforce type constraints.

</>
Copy
#include <iostream>
#include <type_traits> // For std::is_integral
using namespace std;

template <typename T>
void checkType() {
    static_assert(is_integral<T>::value, "Type T must be an integral type"); // Constraint for integral types
    cout << "Type is valid!" << endl;
}

int main() {
    checkType<int>();    // Valid: int is an integral type
    // checkType<float>(); // Uncommenting this line will cause a compile-time error
    return 0;
}

Output:

Type is valid!

Explanation:

  1. The template function checkType uses static_assert to ensure that the provided type T is an integral type.
  2. Calling checkType<int>() succeeds because int is an integral type, but attempting to call checkType<float>() would result in a compile-time error with the specified message.

Example 3: Conditional Compilation with static_assert

Using static_assert, you can enforce constraints based on platform-specific or custom compile-time conditions.

</>
Copy
#include <iostream>
using namespace std;

int main() {
    constexpr bool is64Bit = sizeof(void*) == 8;
    static_assert(is64Bit, "This program requires a 64-bit platform");
    cout << "Running on a 64-bit platform" << endl;
    return 0;
}

Output:

Running on a 64-bit platform

Explanation:

  1. The is64Bit variable is a compile-time constant that checks whether the program is running on a 64-bit platform.
  2. If the condition is false, the compiler halts with the message "This program requires a 64-bit platform".
  3. On a 64-bit platform, the program compiles and runs successfully.

Key Points to Remember about static_assert

  1. static_assert checks conditions during compilation, ensuring early error detection.
  2. It requires a constant expression as its first parameter.
  3. Custom error messages are optional in C++17 and later.
  4. Common use cases include template constraints, platform checks, and enforcing compile-time assumptions.
  5. Using static_assert improves code safety by catching logical errors before runtime.