
[英]C “__builtin_types_compatible_p” function is returning the wrong value for “char*” type
[英]__builtin_classify_type is not returning as defined in typeclass.h
我正在尝试检查给定的宏标记是否是指针(__builtin_classify_type(...) == 5),但我遇到了这个内置函数的定义输出不准确的问题。
经过一些测试后,这是我想出的一个类型数组(其中 x 未知/未找到):
char* classes[] = {"x" , "integer/enum/char/long/size_t" , "x" ,
"x" , "x" , "pointer/void/string/array/function" ,
"x" , "x" , "float/double" ,
"complex", "x" , "x" ,
"struct" , "union" , "x" ,
"x" , "x" , "x" };
将此与 typeclass.h 中的枚举进行比较,
enum type_class
{
no_type_class = -1,
void_type_class, integer_type_class, char_type_class,
enumeral_type_class, boolean_type_class,
pointer_type_class, reference_type_class, offset_type_class,
real_type_class, complex_type_class,
function_type_class, method_type_class,
record_type_class, union_type_class,
array_type_class, string_type_class,
lang_type_class
};
我不关心的大多数类,或者甚至找不到它们的定义来测试(记录、真实、语言等)。我使用 __builtin_classify_type 的全部理由是识别指针,但如果它也匹配 voids ,字符串,arrays,同一个class下的函数,那就真的没用了。
任何人都知道为什么 __builtin_classify_type 返回的值与 typeclass.h 不一致?
对于为什么会发生这种情况,这确实不是一个直接的答案,但如果您还试图识别给定的宏标记是否明确地是一个指针,则更多的是一种解决方法。 不幸的是,如果这个内置函数返回了预期的结果,它会涉及更多的内容。
#define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
#define is_pointer_or_array(p) __builtin_classify_type(p) == 5
char UNREACHABLE_VAR;
#define is_pointer(p) __builtin_choose_expr(is_pointer_or_array(p), \
is_same_type(p, &(*__builtin_choose_expr(is_pointer_or_array(p), p, &UNREACHABLE_VAR))), 0)
使用 __builtin_classify_type(p),我们可以确定 p 是指针还是数组。 接下来我们需要过滤掉任何 arrays,因此我们检查整个变量 p 是否与该变量的第一个元素的类型相同。 数组的类型不同(数组与指针),而数组指针的类型与单个元素的类型相同。 总的来说,只有当标记 p 是指针类型时才会返回 true。
注意: __builtin_choose_expr() 由于忽略编译器错误的方式的限制,在同一个表达式中重复使用了两次。 我们被迫尽可能地分解语句,以便如果它返回 false,则语句在语法上仍然是正确的(即使 false 分支无法到达)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.