Static Assert In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Static Assert In C++

Static Assert In C++

BLUF: Mastering Static Assert In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Static Assert In C++

C++ is renowned for its efficiency. Learn how Static Assert In C++ enables low-level control and high-performance computing in the tutorial below.

In this post, we will explore the static_assert feature in C++ along with its syntax, parameters, and illustrations.

What is the static_assert?

The staticassert feature is an intrinsic part of C++ programming language. It enables developers to validate statements at compile time. This functionality was incorporated into C++ in the version C++11. The staticassert feature comprises two primary components: conditions and messages. The condition necessitates a constant expression, while the message must be a literal. Its primary purpose is to avert potential errors from surfacing during runtime, thereby enhancing code reliability and clarity.

Syntax:

It has the following syntax:

Example

static_assert(constant_expression, string_literal);

Parameters:

  • The constant expression will give the constant Boolean value at compile time.
  • String_literal is an error message that must be displayed when the constant expression is evaluated as false. Sometimes, the programmer does not give the message or the string literal. In that case, a default message is displayed.
  • Static_assert will ensure that the condition is met only at compile time, not during the program's execution. However, the runtime assertions are used for debugging to catch unexpected conditions during execution.
  • Example:

Let's consider a code example to demonstrate the usage of the static_assert function in C++.

Example

#include <iostream>
#include <type_traits>
using namespace std;
template<typename T>
void printSize() {
    static_assert(sizeof(T) >= 4, "Size of type must be at least 4 bytes");
    cout << "Size of type: " << sizeof(T) << " bytes" << endl;
}
int main() {
    printSize<int>();       // This will work
    printSize<short>();  // This will fail
    return 0;
}

Output:

Explanation:

  • In this example, the program has a function template named printSize , which is used to print the size of a given type. So here, we used the assert feature so that if the size of the type is less than 4 bytes, the error message is displayed in the console.
  • There are many situations where we use the static_assert Some of them are checking constant expressions, checking the type sizes, validating configuration parameters, checking Enum values, validating template parameters, and validating compile-time computations, which are also used to ensure API compatibility.
  • Before introducing this feature, other techniques are used to achieve a similar functionality for compile-time assertions. Some of them:
  • The #error directive will stop the program when a particular condition is met. Using Enumerations to trigger a compilation error when the condition wasn't met.
  • Situations where the static_assert feature is commonly used in programming.
  • Checking constant expressions:

Let's consider a program to showcase the utilization of the static_assert function in C++ for validating constant expressions.

Example

#include <iostream>
using namespace std;
constexpr int MAX_SIZE = 100;
static_assert(MAX_SIZE > 0, "MAX_SIZE must be greater than zero");
int main() {
    cout << "MAX_SIZE: " << MAX_SIZE << endl;
    return 0;
}

Output:

Explanation:

In this code snippet, a constant expression variable is declared with a value of 100. Subsequently, an assertion verifies if the MAXSIZE exceeds 0. If this condition is not met, error messages will indicate that the MAXSIZE should be above zero.

Validation the configuration parameters:

Let's consider a sample program to demonstrate how to use the functionality for validating configuration settings.

Example

#include <iostream>
using namespace std;
constexpr int BUFFER_SIZE = 3000;
static_assert(BUFFER_SIZE >= 512 && BUFFER_SIZE <= 2048, "BUFFER_SIZE must be between 512 and 2048");
int main() {
    cout << "BUFFER_SIZE: " << BUFFER_SIZE << endl;
    return 0;
}

Output:

Explanation:

In the software, a variable BUFFERSIZE is set to a value of 3000. Subsequently, an assert statement will validate if the BUFFERSIZE falls between the values 512 and 1048. If the BUFFER_SIZE is outside of this range, an error message will be generated.

Validating the compile time computations:

Let's consider an example to showcase how the static_assert is employed to validate compile-time computations:

Example

#include <iostream>
using namespace std;
constexpr int Compute(int x) {
    return x * 2;
}
static_assert(Compute(5) == 10, "Invalid computation result");
int main() {
    cout << "Result of computation: " << Compute(5) << endl;
    return 0;
}

Output:

Explanation:

This software showcases compile-time calculations. It is employed to validate the accuracy of computations during compile-time.

To verify size compatibility

Let's consider an example to validate size compatibility by using the static_assert function in C++.

Example

#include <iostream>
using namespace std;
struct Point {
    int x, y;
};
static_assert(sizeof(Point) == 8, "Point struct does not have expected size");
int main() {
    cout << "Size of Point struct: " << sizeof(Point) << " bytes" << endl;
    return 0;
}

Output:

Explanation:

Here, the static_assert functionality is employed to verify if the size of the specified struct is 8 bytes. In case the size is indeed 8 bytes, compilation proceeds smoothly without encountering any errors, and the size of the point struct is shown; if not, it outputs a message indicating that the point struct does not match the anticipated size.

Disabling the code for unsupported feature:

Let's consider a demonstration program to deactivate the code related to an unsupported functionality in C++.

Example

#include <iostream>
using namespace std;
#ifdef NO_FEATURE
static_assert(0, "This code section is not supported");
#endif
int main() {
    cout << "Code section is supported!" << endl;
    return 0;
}

Output:

Using feature without the string_literal

Let's consider a scenario to showcase the static_assert feature in C++ without employing the message parameter.

Example

#include <iostream>
using namespace std;
struct Point {
    long x, y;
};
static_assert(sizeof(Point) == 16, "Point should be 16 bytes");

int main() {
    cout << "Size of Point struct: " << sizeof(Point) << " bytes" << endl;
    return 0;
}

Output:

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience