C语言中有没有办法判断表达式是结构体还是联合体?[closed]

rn0zuynd  于 2023-01-08  发布在  其他
关注(0)|答案(1)|浏览(104)

昨天关门了。
这篇文章是昨天编辑并提交审查的。
Improve this question
我可以用_Generic C11特性来判断一个表达式是一个浮点值(还是一个整数)。但是有没有办法在编译时判断出它是struct还是union呢?例如,有没有一个非标准的gcc特性可以提供帮助呢?

ozxc1zmp

ozxc1zmp1#

可以使用_Generic来查找变量x的类型是struct foo还是union bar,但是不能一般地查找它是struct还是union(并且不关心它是哪个结构体/联合体)。

#include <stdio.h>

#define get_type(x) _Generic((x), \
    struct foo: printf("%s = struct foo\n", #x), \
    union bar: printf("%s = union bar\n", #x), \
    default: printf("%s = something else\n", #x))

struct foo
{
    int x;
};

union bar
{
    int y;
};

struct baz
{
    int z;
};

int main(void)
{
    struct foo x;
    union bar y;
    struct baz z;
    get_type(x);
    get_type(y);
    get_type(z);
}

输出:

x = struct foo
y = union bar
z = something else

相关问题