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
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
trueorfalse. - 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.
#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:
- The
static_assertensures thatsizeof(int)is 4 bytes. If not, the compiler will produce an error with the custom message. - Since the condition evaluates to
trueon 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.
#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:
- The template function
checkTypeusesstatic_assertto ensure that the provided typeTis an integral type. - Calling
checkType<int>()succeeds becauseintis an integral type, but attempting to callcheckType<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.
#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:
- The
is64Bitvariable is a compile-time constant that checks whether the program is running on a 64-bit platform. - If the condition is
false, the compiler halts with the message"This program requires a 64-bit platform". - On a 64-bit platform, the program compiles and runs successfully.
Key Points to Remember about static_assert
static_assertchecks conditions during compilation, ensuring early error detection.- It requires a constant expression as its first parameter.
- Custom error messages are optional in C++17 and later.
- Common use cases include template constraints, platform checks, and enforcing compile-time assumptions.
- Using
static_assertimproves code safety by catching logical errors before runtime.
