c 语言中如何判断两个类型是否相同?

如果你熟悉C语言,应该知道这个问题的答案是no.
在其他高级语言中这个这个要求很容易满足,但在C语言标准中没有提供类型判断功能.
说到这儿,这话题好像应该结束了。
但是,这个问题的答案其实并不是绝对是NO,虽然C语言标准中并没有提供类型判断的能力,但不同的C编译器在实现时会根据需要对C语言提供扩展功能。比如GNU C(gcc).
gcc 通过内置函数(Built-in Function) __builtin_types_compatible_p为C语言提供了运行时的类型判断功能:
示例如下:

#include <stdio.h>
#include <stdlib.h>
void test(int x){
    // 判断x是否为void类型
    if(__builtin_types_compatible_p(typeof(x),void)){
        puts("is void");
    }else{
        puts("is not void");
    }
}
int main(void) {
    test(2);
    return EXIT_SUCCESS;
}

输出

is not void

上面的代码实现判断类型是否为void,因为__builtin_types_compatible_p是编译内置函数,所以直接在宏定义中调用,所以上面的判断可以定义成一个简单的函数宏

#define __type_is_void(expr) __builtin_types_compatible_p(typeof(expr), void)

关于__builtin_types_compatible_p的详细说明参见《Other Built-in Functions Provided by GCC》

再次提请注意:
__builtin_types_compatible_p是GCC提供的C语言扩展的功能,在其他编译器并不适用。

参考资料

《Other Built-in Functions Provided by GCC》
《Extensions to the C Language Family》 GNU的C语言扩展全部说明
《How to check typeof for void value at compile time?》

猜你喜欢

转载自blog.csdn.net/10km/article/details/80756389