C Library - static_assert() macro



The C assert library static_assert() macro is a powerful tool introduced in the C11 standard that allows you to perform compile-time assertions. This means that you can check certain conditions at compile time rather than at runtime, catching potential errors early in the development process.

Syntax

Following is the C library syntax of the static_assert() macro −

static_assert (boolean_expression, message);

Parameters

This macro accepts following parameters −

  • boolean_expression − This is a constant expression that the compiler evaluates at compile time. If this expression evaluates to 0 (false), the compilation fails.

  • message − This is a string literal that provides a description of the error when the assertion fails. This message is displayed during compilation if the assertion fails.

Return Value

This macro does not return a value. Instead, it either allows the compilation to proceed if the assertion is true or causes a compile-time error if the assertion is false.

Example 1: Ensuring Size of a Data Type

This example checks if the size of int is 4 bytes. If not, the compilation fails with the message "int must be 4 bytes".

#include <assert.h>
static_assert(sizeof(int) == 4, "int must be 4 bytes");
int main() {
   return 0;
}

Output

The above code produces following result−

error: static assertion failed: "int must be 4 bytes"

Example 2: Checking Structure Alignment

In this example, we use the offsetof macro to ensure that the int b member of MyStruct is aligned to a 4-byte boundary. If not, the compilation fails.

#include <assert.h>
struct MyStruct {
   char a;
   int b;
};
static_assert(offsetof(struct MyStruct, b) % 4 == 0, "int b must be aligned to 4 bytes");
int main() {
   return 0;
}

Output

After execution of above code, we get the following result

error: static assertion failed: "int b must be aligned to 4 bytes"
Advertisements