问题描述
int a = 5;
double b;
//the expected result is "0",but it raises an error instead...
printf("%d",typeof(a) == typeof(b));
解决方法
您可以通过删除gcc扩展名并使用标准C _Generic
来获得所需的行为:
#define my_typeof(x) _Generic((x),int: 1,double: 2)
printf("%d",my_typeof(a) == my_typeof(b));
唯一的问题是您必须手动键入对每种类型的支持。
, GCC具有一个名为__builtin_types_compatible_p
的内置函数,该函数接受两个类型(而不是表达式)的参数,如果类型兼容,则返回int
值1,否则返回0。
OP的示例可以写为:
int a = 5;
double b;
printf("%d",__builtin_types_compatible_p(typeof(a),typeof(b)));
内置函数: int __ builtin_types_compatible_p ( type1 , type2 )
您可以使用内置函数
__builtin_types_compatible_p
来确定两种类型是否相同。如果类型 type1 和 type2 的非限定版本(属于类型,而不是表达式)兼容,则此内置函数返回1,否则返回0。此内置函数的结果可用于整数常量表达式。
此内置函数忽略顶级限定符(例如
const
,volatile
)。例如,int
等效于const int
。类型
int[]
和int[5]
是兼容的。另一方面,int
和char *
在特定体系结构上不兼容,即使它们的类型大小相同。同样,在确定相似性时要考虑指针间接的数量。因此,short *
与short **
不同。此外,如果两个类型定义的类型的基础类型兼容,则认为它们是兼容的。
enum
类型不被视为与另一enum
类型兼容,即使它们都与同一整数类型兼容;这就是C标准指定的内容。例如,enum {foo,bar}
与enum {hot,dog}
不相似。您通常在代码中使用此函数,其执行会根据参数的类型而有所不同。例如:
#define foo(x) \ ({ \ typeof (x) tmp = (x); \ if (__builtin_types_compatible_p (typeof (x),long double)) \ tmp = foo_long_double (tmp); \ else if (__builtin_types_compatible_p (typeof (x),double)) \ tmp = foo_double (tmp); \ else if (__builtin_types_compatible_p (typeof (x),float)) \ tmp = foo_float (tmp); \ else \ abort (); \ tmp; \ })
注意:此构造仅适用于C。