Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is static_assert in C?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

c

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring