简体   繁体   English

在三元运算符中隐式转换为 void*?

[英]Implicit cast to void* in ternary operator?

I know typed pointers can be implicitly cast to void* when passed to a function expecting a void* argument, but I didn't expect to see it in the ternary op (at least I think that's what's going on).我知道当传递给 function 期望void*参数时,类型化的指针可以隐式转换为void* * ,但我没想到会在三元操作中看到它(至少我认为这是正在发生的事情)。

Consider this simplified code:考虑这个简化的代码:

int * dude() {
    float * f = NULL;
    int * i = NULL;
    return (0 ? f : i);  // pointer type mismatch in conditional expression (good: this is what I want)
}

But if I cast i to void* :但是,如果我将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?
}

I'll go one step further and intentionally return f :我将 go 更进一步并有意返回f

int * dude() {
    float * f = NULL;
    int * i = NULL;
    return (1 ? f : (void*)i);  // again no error... is f being converted to void*?
}

I expected an error in both the 2nd & 3rd examples, but I don't get one.我预计第二个和第三个示例都会出错,但我没有得到一个。 Can someone explain what is going on here?有人可以解释这里发生了什么吗? Thanks!谢谢!

The standard explicitly says that if both operands of the conditional operator are pointers and one is void* (not including a null-pointer constant), then the result is void* .标准明确规定,如果条件运算符的两个操作数都是指针,一个是void* (不包括空指针常量),则结果为void* From C11 6.5.15/6:从 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.如果第二个和第三个操作数都是指针,或者一个是 null 指针常量,另一个是指针,则结果类型是指向一个类型的指针,该类型由两个操作数引用的类型的所有类型限定符限定。 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;如果一个操作数是 null 指针常量,则结果具有另一个操作数的类型; 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 的指针,在这种情况下,结果类型是指向适当限定版本的 void 的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM