2

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.

Vada Poché
  • 763
  • 5
  • 16
Zebrafish
  • 11,682
  • 3
  • 43
  • 119

4 Answers4

4

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.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • One argument I can come up with is that in case of explicitly comparing to `nullptr` you'll get a compilation error if you accidentally use a non-pointer variable. Since types which are implicitly convertible to `bool` are pretty common, it may serve as an additional compile-time check that you've typed what you actually had been thinking about. – Alex Che Oct 19 '22 at 16:09
3

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

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.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121
  • 1
    In C the result is either `1` or `0`. In C++ it's `true` or `false`. The distinction here is that in C its type is `int` and in C++ its type is `bool`. – Pete Becker Apr 06 '17 at 14:02
0
  1. 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.

  2. return ptr ? 1 : 0; will also check ptr for a null pointer. You may still use the earlier version for readibility

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31