[Macro definition] - compile-time check (1)

compile-time validation

Functional description

It is used to check whether a condition is true at compile time. If the condition is true, the compilation will fail and the compiler will report an error

On the contrary, if the condition is false, the compilation is normal and there is a return value, returning 0.

Code

/*
 * Force a compilation error if condition is true, but also produce a
 * result (of value 0 and type int), so the expression can be used
 * e.g. in a structure initializer (or where-ever else comma expressions
 * aren't permitted).
 */
#define BUILD_BUG_ON_ZERO(e) ((int)(sizeof(struct {
      
       int:(-!!(e)); })))

Parameter e represents the expression used for judgment

sample code

Normal compilation example

#include <stdio.h>

#define BUILD_BUG_ON_ZERO(e) ((int)(sizeof(struct {
      
       int:(-!!(e)); })))

int main(void)
{
    
    
    printf("Compilation successful %d.\n", BUILD_BUG_ON_ZERO(0));

    return 0;
}

result print

Compilation successful 0.

Compile error example

#include <stdio.h>

#define BUILD_BUG_ON_ZERO(e) ((int)(sizeof(struct {
      
       int:(-!!(e)); })))

int main(void)
{
    
    
    printf("Compilation successful %d.\n", BUILD_BUG_ON_ZERO(1));

    return 0;
}

compile error message

test.c: In function ‘main’:
test.c:3:51: error: negative width in bit-field ‘<anonymous>3 | #define BUILD_BUG_ON_ZERO(e) ((int)(sizeof(struct {
    
     int:(-!!(e)); })))
      |                                                   ^
test.c:7:44: note: in expansion of macro ‘BUILD_BUG_ON_ZERO’
    7 |     printf("Compilation successful %d.\n", BUILD_BUG_ON_ZERO(1));

The result after preprocessing

gcc -E test.c -> test.i
int main(void)
{
    
    
    printf("Compilation successful %d.\n", ((int)(sizeof(struct {
    
     int:(-!!(1)); }))));

    return 0;
}

code analysis

!!e

Perform two logical NOT operations on the condition e to get 逻辑值the result 0 or 1. Returns 0 if the result of the expression e is 0, and returns 1 if it is a non-zero value.

struct {int:-!!(e); }

If the result of the expression e is 0, the structure struct {int:0;} is obtained, which is an anonymous bit field structure with a bit field width of 0.

If the result of the expression e is 1, then a structure is obtained struct {int:-1;}, and a compilation error occurs. Since the width of a bit field cannot be negative, a compilation error prompts an error error: negative width in bit-field <anonymous>.

sizeof(struct {int:-!!(e); })

If the result of the expression e is 0, the size of the anonymous structure is calculated using the sizeof operator struct {int:0;}, and the return value of the macro is 0.

Reference Code

  • https://blog.csdn.net/u012028275/article/details/127478561

Guess you like

Origin blog.csdn.net/tyustli/article/details/131979287