Understanding Static assertions (Static_assert in C11)

In this blog post, you will learn the _Static_assert in C with its application. you will also learn how to stop the compiling process if the condition is not true (tests an assertion at compile time). Basically, static assertions are a way to control the compilation process. If the specified constant expression is false, the compiler displays the specified error message and stops the compiling process. If it isn’t, there’s no effect. So let’s first understand what is _Static_assert in C?

 

What is _Static_assert in C?

A _static_assert is a keyword introduced in C11. It is defined in the <assert.h> header file. This keyword is also available in form of macro static_assert, available in the header <assert.h>.

 

Syntax of _Static_assert Keyword:

_Static_assert ( expression , message )		(since C11)

_Static_assert ( expression )		(since C23)

Parameters

constant-expression:

The constant expression must be an integer constant expression. If the value of the constant expression is non-zero, the declaration has no effect. Otherwise, the constraint is violated and the implementation will produce a diagnostic message which should include the text of the string literal if present.

string-literal:

The message displayed if constant-expression evaluates to zero (false). The message must be made using the base character set of the compiler. The characters can’t be multibyte or wide characters.

 

C program to understand working of Static_assert function:

Below mentioned C example code shows the usage of Static_assert().

#include<stdio.h>
#include <assert.h>

enum Items
{
    A,
    T,
    I,
    C,
    l,
    E,
    W,
    O,
    R,
    L,
    D,
    LENGTH
};

int main()
{
    // _Static_assert is a C11 keyword
    _Static_assert(LENGTH == 11, "Expected Items enum to have eleven elements");

     // This will produce an error at compile time
     //if int size greater than 16
    _Static_assert(sizeof(int) == 2, "Expecting 16 bit integers");

    return 0;
}

Output:

Static_assert in C

 

Explanation:

In my setup size of int is 4 bytes. So you can see I am getting compiler errors. The program will compile successfully on setup which has the size of int is 2 bytes.

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *