Broad Network


Static Assertions in the C Computer Language

Part 37 of the Complete C Course

Foreword: Static Assertions in the C Computer Language

By: Chrysanthus Date Published: 22 Jun 2024

Introduction

The "_Static_assert();" declaration is used for diagnosis and debugging of a program. The syntax is:

    _Static_assert ( constant-expression , string-literal ) ;
    _Static_assert ( constant-expression ) ;

With the second statement, if the constant-expression results in 0, the compilation will stop, an error message will be issued; and all the code below this assert declaration, will not be compiled, and hence, not executed. 0 means false. If the constant-expression results in any integer other than 0, e.g. +1 or -1, then compilation will not stop, and all the code below this assert declaration will compile and hence, execute; everything being equal. Any integer other than 0, means false. The following declaration was made in the C main() function, in the author's computer (gcc compiler):

            _Static_assert (0);

Compilation stopped and an error message was issued. The following declaration was made in the C main() function, in the author's computer:

            _Static_assert (+1);

Compilation did not stop and no error message was issued. The following declaration was made in the C main() function, in the author's computer:

            _Static_assert (-1);

Compilation did not stop and no error message was issued.

For the first statement in the syntax above, string-literal is text written by the programmer. In case an error occurs, the text written by the programmer is issued along side the text from the C compiler. The text written by the programmer should give more clarity in the overall error message. That is, in case constant-expression is 0. Test the following code:

    #include <stdio.h>
   
    int main(int argc, char *argv[])
        {
            _Static_assert (0, "something went wrong!");
            
            printf("seen\n");

            return 0;
        }

The error message outputted, includes "something went wrong!". Read and test the following code:

    #include <stdio.h>
   
    int main(int argc, char *argv[])
        {
            _Static_assert (-1, "something went wrong!");
            
            printf("seen\n");

            return 0;
        }

The output is "seen", because -1 means true, in this situation. So no error message, whatsoever was issued. A constant-expression that may result in false (0) , is "1 == 2" , without the quotes. A constant expression that may result in true, is "3 == 3" or "4 - 5" , without the quotes.



Related Links

More Related Links

Cousins

BACK NEXT

Comments