What is static_assert in C?

Share

static_assert is a keyword defined in the <assert.h> header. It is available in the C11 version of C.

static_assert is used to ensure that a condition is true when the code is compiled.

The condition must be a constant expression. In case of failure, an error message is displayed to alert the user.

Here’s the syntax:

static_assert(expression, message);
Flow of Events with a static assertion

Code

#include <assert.h>
#include <stdio.h>
int main() {
enum week_end { Sat, Sun, len = 2 };
static_assert(len == 2, "The weekend is exactly 2 days.");
printf("Success!");
}

Here, we’ve created an enumeration that represents the weekend. The len has been specifically assigned the integer constant 2. Our static assertion verifies the condition len == 2 and prints Success ! on a successful compilation. Let’s try changing the value for len as follows:

#include <assert.h>
#include<stdio.h>
int main() {
enum week_end { Sat, Sun, len = 3 };
static_assert(len == 2, "The weekend is exactly 2 days.");
printf("Success!");
}

In this case, we are dealt with a compiler error. The error message is displayed as expected.

Copyright ©2024 Educative, Inc. All rights reserved