Defending the ternary operator

Anders Hammarquist iko at cd.chalmers.se
Tue Feb 11 23:56:02 CET 2003


In article <b27i4g$u5t$1 at slb9.atl.mindspring.net>,
Andrew Dalke <adalke at mindspring.com> wrote:
>Paul Rubin on my analysis of some C++ code's use of "?:" :
>> > EXAMPLE 1: (used 6 times)
>> >
>> >   return arr[i] & mask ? true : false;
>
>> > If C++ does have a boolean type, then this isn't needed.  Even
>> > when it didn't exist, it would have been easy to define, just like
>> > the values 'true' and 'false' were defined.
>>
>> It's still needed, if you want the function to return true or
>> false, instead of considering 0x1 and 0x04000 to be equivalent.
>
>If C++ has a bool type and builtin true/false then the C++ code
>quoted above can be replaced with
>
>   return bool(arr[i] & mask)

Since we're in the process of tearing all the other languages apart,
I offer this for C/C++ bool when you want a 1 or 0 result (remember,
this is C, and C loves punctuation):

return !!(arr[i] & mask);

While I don't think that's particularly beautiful either, not not
parses easier than a ternary for me at least. I also suspect that
this construct would be a lot more common if C didn't have a
ternary. ;-)

/Anders

-- 
 -- Of course I'm crazy, but that doesn't mean I'm wrong.
Anders Hammarquist                                  | iko at cd.chalmers.se
Physics student, Chalmers University of Technology, | Hem: +46 31 88 48 50
G|teborg, Sweden.           RADIO: SM6XMM and N2JGL | Mob: +46 707 27 86 87




More information about the Python-list mailing list