在三元运算符中隐式转换为 void*?
Implicit cast to void* in ternary operator?
我知道当传递给需要 void*
参数的函数时,类型化指针可以隐式转换为 void*
,但我没想到会在三元操作中看到它(至少我认为这就是正在发生的事情)。
考虑这个简化的代码:
int * dude() {
float * f = NULL;
int * i = NULL;
return (0 ? f : i); // pointer type mismatch in conditional expression (good: this is what I want)
}
但是如果我将 i
转换为 void*
:
int * dude() {
float * f = NULL;
int * i = NULL;
return (0 ? f : (void*)i); // no error! it suddenly likes f? or is f being optimized out?
}
我会更进一步 return f
:
int * dude() {
float * f = NULL;
int * i = NULL;
return (1 ? f : (void*)i); // again no error... is f being converted to void*?
}
我预计第二个和第三个示例都会出错,但我没有得到。有人可以解释这里发生了什么吗?谢谢!
标准明确规定,如果条件运算符的两个操作数都是指针,其中一个是void*
(不包括空指针常量),则结果是void*
。来自 C11 6.5.15/6:
If both the second and third operands are pointers or one is a null pointer constant and the other is a pointer, the result type is a pointer to a type qualified with all the type qualifiers of the types referenced by both operands. Furthermore, if both operands are pointers to compatible types or to differently qualified versions of compatible types, the result type is a pointer to an appropriately qualified version of the composite type; if one operand is a null pointer constant, the result has the type of the other operand; otherwise, one operand is a pointer to void or a qualified version of void, in which case the result type is a pointer to an appropriately qualified version of void.
我知道当传递给需要 void*
参数的函数时,类型化指针可以隐式转换为 void*
,但我没想到会在三元操作中看到它(至少我认为这就是正在发生的事情)。
考虑这个简化的代码:
int * dude() {
float * f = NULL;
int * i = NULL;
return (0 ? f : i); // pointer type mismatch in conditional expression (good: this is what I want)
}
但是如果我将 i
转换为 void*
:
int * dude() {
float * f = NULL;
int * i = NULL;
return (0 ? f : (void*)i); // no error! it suddenly likes f? or is f being optimized out?
}
我会更进一步 return f
:
int * dude() {
float * f = NULL;
int * i = NULL;
return (1 ? f : (void*)i); // again no error... is f being converted to void*?
}
我预计第二个和第三个示例都会出错,但我没有得到。有人可以解释这里发生了什么吗?谢谢!
标准明确规定,如果条件运算符的两个操作数都是指针,其中一个是void*
(不包括空指针常量),则结果是void*
。来自 C11 6.5.15/6:
If both the second and third operands are pointers or one is a null pointer constant and the other is a pointer, the result type is a pointer to a type qualified with all the type qualifiers of the types referenced by both operands. Furthermore, if both operands are pointers to compatible types or to differently qualified versions of compatible types, the result type is a pointer to an appropriately qualified version of the composite type; if one operand is a null pointer constant, the result has the type of the other operand; otherwise, one operand is a pointer to void or a qualified version of void, in which case the result type is a pointer to an appropriately qualified version of void.