Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

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*:

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:

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!

like image 693
textral Avatar asked Mar 01 '21 13:03

textral


Video Answer


1 Answers

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*. From 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.

like image 159
interjay Avatar answered Oct 17 '22 19:10

interjay