Whenever I see people using the ternary operator they often allow the implicit conversion to a boolean true or false check, for example:
int a = 5;
return a ? true : false;
However I've heard it's good practice in many cases to be explicit, for example to check if a pointer is nullptr instead of implicitly doing a boolean check. With this in mind, I wanted to do the following:
int* ptr = nullptr;
return ptr == nullptr ? 0 : 1;
This looks a little strange to me, and raises a bunch of questions of how exactly it parses this. But my main question is do I need brackets around the ptr == nullptr part? If not for necessity then I assume it helps for clarity? Or is it better and simpler just to do:
return ptr ? 1 : 0;
Thanks.
The conditional operator has lower precedence than postfix operators, unary operators, cast operators, pointer-to-member operators, arithmetic operators, comparison operators, bitwise operators, and logical operators. Therefore, you do not need parentheses around ptr == nullptr
.
Anyway, comparing to nullptr
directly rather than coercing to bool does not have any concrete advantages. Some people consider it to be better style, but there is really no technical argument for this. So feel free to ignore it if you want.
If you do decide to coerce to bool directly, writing !!a
or !!ptr
is idiomatic; no need for the conditional expression.