【问题标题】:Why does the typeof function not working in C为什么 typeof 函数在 C 中不起作用
【发布时间】:2020-09-11 09:15:46
【问题描述】:
  • 我使用的是 GCC 编译器(版本 9.2.0)
  • 我想在 C 中使用 typeof 函数,但它会引发错误(error: expected expression before 'typeof'
  • 如果您需要更多信息,尽管问我。
int a = 5;
double b;
//the expected result is "0", but it raises an error instead...
printf("%d", typeof(a) == typeof(b));

【问题讨论】:

  • 它引发错误的原因与int == double 引发错误的原因相同。
  • C++ 有 typeid 可以做到这一点,但我认为 C 还没有。
  • @tadman - 更准确的 C++ 等效项是 decltype
  • @StoryTeller-UnslanderMonica 更好,是的!
  • GCC 有__builtin_types_compatible_p(TYPE1, TYPE2)

标签: c gcc compiler-errors typeof


【解决方案1】:

您可以通过删除 gcc 扩展并使用标准 C _Generic 来获得您想要的行为:

#define my_typeof(x) _Generic((x), int: 1, double: 2)

printf("%d", my_typeof(a) == my_typeof(b));

唯一的问题是您必须手动输入对每种类型的支持。

【讨论】:

  • 谢谢',它可以了,唯一的问题是,你知道为什么我不能使用这个功能吗? (我正在使用 Code::Blocks 顺便说一句)
  • @Mobento 什么功能?打印?
  • 我的意思是为什么这个功能(typeof)对我不起作用而在其他系统中起作用
  • @Mobento 因为你用错了,如cmets所示?
【解决方案2】:

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判断两种类型是否相同。

如果类型 type1type2 的非限定版本(它们是类型,而不是表达式)兼容,则此内置函数返回 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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 2012-02-14
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多