Reputation: 13938
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.
Upvotes: 2
Views: 1109
Reputation: 8614
You do not need the brackets around ptr == nullptr
in your second example. This is because by order or precedence, the ==
operator is higher than the ternary operator. You can add it for clarity, though.
return ptr ? 1 : 0;
will also check ptr
for a null pointer. You may still use the earlier version for readibility
Upvotes: 0
Reputation: 41625
The most readable and idiomatic way is:
return ptr != nullptr;
The language already guarantees that the result of that expression is either 1 or 0, therefore you should not write that explicitly.
Upvotes: 0
Reputation: 206607
From a syntactic point of view,
return ptr == nullptr ? 0 : 1;
is perfectly alright. From a readability point of view
return (ptr == nullptr) ? 0 : 1;
is much better. YMMV.
Upvotes: 3
Reputation: 119219
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.
Upvotes: 4