empty arrays and cast(bool): WAT
Steven Schveighoffer
schveiguy at yahoo.com
Mon Mar 5 05:27:25 PST 2012
On Sat, 18 Feb 2012 21:01:55 -0500, Timon Gehr <timon.gehr at gmx.ch> 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.
Just to weigh in:
1. The most intuitive and useful thing is to check for arr.length.
2. Given that there are valid cases for checking null vs. empty, I think
there should be a way to find usages of if(arr) for fixing legacy code.
To disallow if(arr) simply because of legacy code is a step in the *wrong*
direction. The experience with arrays is going to be a major contributing
factor to the enjoyment of using D. I'd rather see the compiler show you
where cases of if(arr) appear, and allow you to judge whether those should
be arr.ptr or not.
I agree with Timon, let's make it more intuitive, and break code, and let
those people be able to fix that code somehow. If this means deprecating
it for a time, so be it.
-Steve
More information about the Digitalmars-d
mailing list