empty arrays and cast(bool): WAT

Jonathan M Davis jmdavisProg at gmx.com
Sat Feb 18 18:23:52 PST 2012


On Sunday, February 19, 2012 03:01:55 Timon Gehr wrote:
> Why does the following code behave funny?
> 
> void main(){
>      string x = " "[1..1];
>      writeln(cast(bool)x); // true
>      char[] y = [' '][1..1];
>      writeln(cast(bool)y); // false
> }
> 
> Is there any reason for empty arrays to evaluate to true? This is very
> bug prone.

Because they're not null. _null_ is what evaluates to false, not an empty 
array. But the fact that == treats null and [] as the same thing _does_ 
understandably cloud things a bit.

But

if(arr)

is lowered to

if(cast(bool)arr)

which checks for null, not empty. So, this is fully expected. If you want to 
check whether an array is empty, then check whether it's empty, not whether 
it's true.

- Jonathan M Davis


More information about the Digitalmars-d mailing list