我有一个带有联合和枚举的结构。我制作了一个宏,它输出结构的复合文字,根据传递给宏的类型设置联合的种类和数据使用_Generic。
示例代码:
#include <stdio.h>
struct mystruct {
enum { K_NUM, K_STR } kind;
union { int num; char * str; };
};
#define MYSTRUCT(X) _Generic((X), \
int: (struct mystruct){K_NUM, .num=X}, \
char *: (struct mystruct){K_STR, .str=X} \
)
void print_mystruct(struct mystruct s) {
switch (s.kind) {
case K_NUM: printf("mystruct (num): %d\n", s.num); break;
case K_STR: printf("mystruct (str): %s\n", s.str); break;
}
}
int main() {
print_mystruct(MYSTRUCT(2));
print_mystruct(MYSTRUCT("test"));
}
它确实使用 gcc 编译,然后正确运行它输出:
mystruct (num): 2
mystruct (str): test
但是我得到了所有这些编译警告:
c.c: In function 'main':
c.c:21:26: warning: initialization of 'char *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
21 | print_mystruct(MYSTRUCT(2));
| ^
c.c:10:40: note: in definition of macro 'MYSTRUCT'
10 | char *: (struct mystruct){K_STR, .str=X} \
| ^
c.c:21:26: note: (near initialization for '(anonymous).<anonymous>.str')
21 | print_mystruct(MYSTRUCT(2));
| ^
c.c:10:40: note: in definition of macro 'MYSTRUCT'
10 | char *: (struct mystruct){K_STR, .str=X} \
| ^
c.c:22:26: warning: initialization of 'int' from 'char *' makes integer from pointer without a cast [-Wint-conversion]
22 | print_mystruct(MYSTRUCT("test"));
| ^~~~~~
c.c:9:37: note: in definition of macro 'MYSTRUCT'
9 | int: (struct mystruct){K_NUM, .num=X}, \
| ^
c.c:22:26: note: (near initialization for '(anonymous).<anonymous>.num')
22 | print_mystruct(MYSTRUCT("test"));
| ^~~~~~
c.c:9:37: note: in definition of macro 'MYSTRUCT'
9 | int: (struct mystruct){K_NUM, .num=X}, \
| ^
我尝试在复合文字中进行强制转换,如下所示:
int: (struct mystruct){K_NUM, .num=(int)X}, \
char *: (struct mystruct){K_STR, .str=(char *)X} \
但我收到不同的警告:
c.c: In function 'main':
c.c:9:37: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
9 | int: (struct mystruct){K_NUM, .num=(int)X}, \
| ^
c.c:22:17: note: in expansion of macro 'MYSTRUCT'
22 | print_mystruct(MYSTRUCT("test"));
| ^~~~~~~~