[Issue 1626] bool spec problem

Matti Niemenmaa see_signature at for.real.address
Tue Oct 30 02:10:40 PDT 2007


Derek Parnell wrote:
> I think that the confusion comes about because the form...
> 
>   if (X)
> 
> where X does not contain a comparison operand, is really shorthand for ...
> 
>   if (X != 0)
> 
> so the expression is already a boolean so no conversion is needed. That is
> to say "if (3 != 0)" returns a boolean already so its not a case of '3'
> being converted to a boolean at all.
> 
> To repeat, "if (X)" is equivalent to "if (X !=0)" and is not equivalent to
> "if (cast(bool)X)".

"if (X != 0)" is equivalent to "if (cast(bool)X)" for all numerical types.
However, "if (cast(bool)X)" also works for objects, arrays, and the like, which
can't be compared to 0.

Thus I'd say it is equivalent to "if (cast(bool)X)", as "if (X)" works for all
types (except structs), as does "if (cast(bool)X)", whereas "if (X != 0)" only
works for int and floating point types. For objects and arrays, it's "if (X !is
null)".

If X is already a boolean, the test done is "X != 0", which is why "if (X)"
works but "if (X == true)" doesn't, when X contains a value which is neither
true nor false.

-- 
E-mail address: matti.niemenmaa+news, domain is iki (DOT) fi


More information about the Digitalmars-d-bugs mailing list