为什么typeof函数在C中不起作用

问题描述

  • 我使用GCC编译器(版本9.2.0)
  • 我想在C语言中使用typeof函数,但会引发错误错误:“ typeof”之前的预期表达式
  • 如果您需要更多信息,请问我。
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)));

来自online documentation

内置函数: int __ builtin_types_compatible_p type1 type2

您可以使用内置函数__builtin_types_compatible_p来确定两种类型是否相同。

如果类型 type1 type2 的非限定版本(属于类型,而不是表达式)兼容,则此内置函数返回1,否则返回0。此内置函数的结果可用于整数常量表达式。

此内置函数忽略顶级限定符(例如constvolatile)。例如,int等效于const int

类型int[]int[5]是兼容的。另一方面,intchar *在特定体系结构上不兼容,即使它们的类型大小相同。同样,在确定相似性时要考虑指针间接的数量。因此,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。