Why is array truth tied to .ptr?

Robert Fraser fraserofthenight at gmail.com
Sun Dec 9 23:18:02 PST 2007


Bill Baxter wrote:
> Here's a little test program:
> 
> void main()
> {
>     void check(int[] l) {
>         if (l) writef("%-10s","true"); else writef("%-10s","false");
>         writef("%-10s", (l is null));
>         writef("%-10s", (l.length==0));
>         writefln;
>     }
> 
>     int[] list;
>     writefln("%-10s%-10s%-10s%-10s",
>              " ", "is true","is null","length==0");
>     writef("%-10s","initial"); check(list);
>     list = new int[10];
>     list = null;
>     writef("%-10s","nulled"); check(list);
> 
>     list = new int[10];
>     list.length = 0;
>     writef("%-10s", "zeroed"); check(list);
> }
> 
> 
> and here's the table it generates:
> 
>           is true   is null   length==0
> initial   false     true      true
> nulled    false     true      true
> zeroed    true      false     true
> 
> Question: which is the bit of information you are more likely interested 
> in knowing:
> 
> a) whether the array is currently empty.
> b) whether the array happens to have a buffer of some unknowable length 
> allocated because of a previous history of operations on it.
> 
> If you answered a) then we think alike.
> 
> So why does the simplest check
> 
>     if(array) { ... }
> 
> tell us b) ?
> 
> In a nutshell,
>    if(array)
> is synonymous with
>    if(array.ptr)
> but I believe it makes much more sense for it to be synonymous with
>    if(array.length)
> since that's the thing you want to be checking 99.9% of the time.
> 
> A little while ago I realized I was making the mistake of checking 
> if(array) all over my code.  It makes a lot of sense to do that if you 
> know Python, since that's how Python works.  But I think Python's way 
> makes a lot more sense than D's way.  So it's hard to remember that the 
> simple and clear   if(array)  is almost always a bug waiting to happen.
> 
> 
> --bb

me too



More information about the Digitalmars-d mailing list