Forbid dynamic arrays in boolean evaluation contexts

Phil Lavoie maidenphil at hotmail.com
Mon Mar 25 09:43:24 PDT 2013


On Monday, 25 March 2013 at 16:14:18 UTC, bearophile wrote:
> Phil Lavoie:
>
>> 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.
>
> Some D programmers come from other languages, where if(arr) 
> means if its len is different from zero.
>
> D dynamic arrays are 2 words, so you can have a length zero 
> with a not-null pointer. So there is space for some semantic 
> confusion.
>
>
>> 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.
>
> D dynamic arrays aren't pointers, they are composed of two 
> words, so you can't assume the semantics is exactly the same.
>
> I think assuming if(arr) means if(!arr.empty) is still better 
> than the current situation :-)
>
> Bye,
> bearophile

Herro,

Of course you can argue that not every programmers come from 
C/C++ background, but, if I'm correct, D is aimed to be a C++ 
replacement, right? On the other hand, C is like the most used 
language on the universe (aliens included), so it makes sense to 
consider its expression semantics first. I am aware that those 
aren't the strongest arguments, but if we'd have to compare 
programmer backgrounds to make a decision regarding expression 
behaviors, I think C should win.

Obviously, slices are not single word pointers, but they are 
pointers after all (or at the very least own one). Just saying 
that comparing a slice for its initial state or an invalid state 
is not the same as checking length, but I think we agree on that.

Where we disagree is on default behavior of if(arr). You think it 
should check for length to be more programmer friendly, or 
rather, avoid unwanted errors (though if I was that programmer, I 
would not think it's friendly at all :( ) whereas I think it 
should act as if it was a pointer in C.

Since it is already the behavior of the language, on a scale of 
10, how would you prioritize your suggestion :D? How much of a 
change do you think it would make? I respect your opinions and 
suggestions, though I have never fell in the trap you presented 
in your opening statement :), nor did I even think someone would.

I do believe that, in any case, this form is best:
if( arr !is null && !arr.empty )

Peace,
Phil


More information about the Digitalmars-d mailing list