Forbid dynamic arrays in boolean evaluation contexts
Phil Lavoie
maidenphil at hotmail.com
Mon Mar 25 08:47:08 PDT 2013
On Sunday, 24 March 2013 at 22:10:06 UTC, bearophile wrote:
> 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
Hi,
IMHO, somebody coming from a C/C++ background (like me) has no
problem realizing that if( var ) means either if not null or if
not 0. There was talk about changing the behavior of if( arr ) to
mean if( !arr.empty ) but I believe this is the worst thing to
do, since it would incorporate some inconsistencies with usual
pointers.
int[] foo() { auto var = new int[ 0 ]; return var; }
int * bar() { auto var = cast( int * )malloc( 0 ); return var; }
void main() {
if( foo() ) {
//Would not pass, since foo is empty.
}
if( bar() ) {
//Would pass, since bar is not null.
}
}
I prefer to have code that explicitly states what is going on
anyways:
if( arr !is null && !arr.empty ) { blablabla; }
Whenever somebody decides to used the abbreviated expression
if(arr), I think that the behavior should be the one of the C
language. I'm not sure it is wise just yet to establish that
whenever somebody test a slice to see if it's null that somebody
also means to test if it is empty.
Interesting idea though.
Cheers!
Phil
More information about the Digitalmars-d
mailing list