Forbid dynamic arrays in boolean evaluation contexts

bearophile bearophileHUGS at lycos.com
Sun Mar 24 15:10:05 PDT 2013


A recent discussion in D.learn reminds me of an enhancement 
request of mine that is sleeping in Bugzilla since years:

http://d.puremagic.com/issues/show_bug.cgi?id=4733


The probles is that in D dynamic arrays can be non-null even when 
they are empty:


import std.stdio;
int[] foo() {
     auto a = [1];
     return a[0..0];
}
void main() {
     auto data = foo();
     if (data)
         writeln("here");
}


This is dangerous, so in D the safe and idiomatic way to test for 
empty arrays is to use std.array.empty().

So my proposal of Issue 4733 is to forbid (with the usual 
warning/deprecation intermediate steps) the use of dynamic arrays 
in a boolean context:


void main() {
     auto a = [1];
     if (a) {} // error, forbidden.
}


So to test empty/null you have to use empty() or "is null":

import std.array: empty;
void main() {
     auto a = [1];
     if (a.empty) {} // OK
     if (a is null) {} // OK
}


Bye,
bearophile


More information about the Digitalmars-d mailing list