Casting an expression to bool means testing for 0 or !=0 for arithmetic types

Pluto pluto at planets.not
Sun Aug 1 02:24:22 PDT 2010


== Quote from Simen kjaeraas (simen.kjaras at gmail.com)'s article
> Pluto <pluto at planets.not> wrote:
> > == Quote from Simen kjaeraas (simen.kjaras at gmail.com)'s article
> >> Pluto <pluto at planets.not> wrote:
> >> > This part has always bothered me. Could somebody please explain to me
> >> the
> >> > rationale behind limiting functions to one usable error code?
> >> Well, traditionally it was done because testing for 0/non-0 is a simple
> >> and fast operation.
> > So speed it is. Was <1 really slower back then?
> Likely not. But the assembly is easier:
> jnz <label>; vs cmp EAX 0; jg <label>;
That might explain things.

> >> Also, boolean logic can be thought of as simple maths,
> >> as AND is multiplication and OR is addition. This only makes sense if
> >> false == 0.
> > false < 1, is what I would expect.
> > It even makes it more symmetrical.
> How?
> Let's start out with a false value f of -1. Now AND it with itself
> (f * f), and you get 1, which is true. This does not seem correct.
Not knowing anything about assembler(and ignoring history), this seems sensible to me:
f is an integral, not a boolean. For it to work like a boolean it needs a cast,
implicit or explicit:
cast(bool); >0?true:false
if(returnsErrorCodes()); implicit cast from return value to bool
f*f; integral operation and should return the multiplication
f&f; bitwise operation and should return bitwise AND
cast(bool) f & cast(bool) f; bitwise operation on booleans
~~
:Pluto



More information about the Digitalmars-d-learn mailing list