What is the meaning of struct enclose by braces?

Viewed 62

Recently, I am tracing some source code. I stuck when I saw following macro.

#define tmp(x)                                          \
((void) ((struct {                                     \
     _Static_assert(sizeof(x) <= 16, "Err"); \
     int dum;                                        \
 }){1})

This macro is for checking whether the size of x is less than 16.

I have two question about this macro.

First, what is struct in following format meaning, did this style has key word?

(struct {                       
     .......                                      
 }){1};

Second, why it put assert inside struct? Why not just call _Static_assert in main?

1 Answers

This "parenthesized declaration and initialization" is known as the compound literal. This syntax feature first appeared in C99. Its basic syntax is:

( type ) { initializer-list }

So what you have here, if we omit the _Static_cast, is (struct { int dum; }){1}, which declares an unnamed structure and creates a compound literal with this structure containing dum==1. The type cast to void simply discards the value, avoiding possible "unused value" warning.

Second, why it put assert inside struct? Why not just call _Static_assert in main?

If you notice, this expands to something that's not terminated with a semicolon ;. (I suppose a missing closing parenthesis ) is your copy-paste mistake.) Thus it can be used as a subexpression, e.g.

#define tmp(x)                               \
((void) ((struct {                           \
     _Static_assert(sizeof(x) <= 16, "Err"); \
     int dum;                                \
 }){1}))

#include <stdio.h>
int main()
{
    const int x=324;
    const double y=(tmp(x), 23.342);
    printf("%g\n", y);
}

Not sure why one would want this, but at least it's made available by the author of this macro for some case when it could be needed.

Related