I know the ternary operator has some surprising restrictions, but I was a bit baffled that this fails to compile for me:
void foo(bool b)
{
int* ptr = ((b) ? NULL : NULL);
}
Obviously that’s the minimum needed to show the problem. The error is:
[BCC32 Error] Unit11.cpp(20): E2034 Cannot convert 'int' to 'int *'
Compiler is the less-than-100%-conforming Embarcadero C++Builder 2010, so a compiler bug is far from impossible…
NOTE: Parens modified to avoid confusion about my intent.
NOTE2: I’d got myself a little confused about how I’d arrived at this construct in the first place, so here’s my excuse: I was getting some compilation errors on a line like a = b? c : d, where b, c and d were all complex expressions. To narrow it down, I replaced c and d with NULLs in order to check if b was the culprit. At this point, everything went to hell in a handcart.
NULLis a macro that expands to0(or some integral constant expression with a value of0, for example,(1 - 1)). It’s not otherwise “special.”Any integral constant expression with a value of zero is usable as a null pointer constant, which is the reason that
int* ptr = 0;is permitted. However, here, the expression isb ? 0 : 0; this is not an integral constant expression (bis not constant); its type isint, which is not implicitly convertible toint*The workaround would be to explicitly specify that you want a pointer type:
The example is a bit contrived, though: usually when one uses the conditional operator, at least one of the arguments is actually a pointer type (e.g.
b ? ptr : 0); when one of the operands is a pointer type, the0is implicitly converted to that same pointer type and thus the type of the entire conditional expression is the pointer type, notint.The only case where you can have this “problem” is where a null pointer constant is used as both the second and third operands of the conditional operator, which is rather odd.