if(arr) now a warning

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Mon Apr 20 11:01:10 PDT 2015


On Monday, April 20, 2015 16:14:39 Kagamin via Digitalmars-d wrote:
> On Sunday, 19 April 2015 at 08:05:46 UTC, Jonathan M Davis wrote:
> > the C folks would think that
> > the current behavior of it being equivalent to if(arr is null)
> > would be more
> > intuitive, since they're used to thinking of arrays as pointers.
>
> Are they used to disregard value types too? I don't see it
> working in C: http://ideone.com/rzSSlx

An array in C is a pointer, not a struct. So, the obvious thing for a C
programmer when they see

if(arr)

would be to think that it was equivalent to

if(arr != NULL)

or

if(arr != 0)

and _not_ something like

if(arr.length != 0)

particularly since arrays don't even know their length in C. Obviously, if
they're dealing with a struct, then it's not the same, and D arrays are
technically structs, but regardless, if you're a C/C++ programmer and you're
using a struct to hold the length of your array along with its pointer, and
you were going to decide what

if(arr)

is going to mean, then checking whether ptr was null or not would be the
obvious thing (which _can_ be defined in C++ via an overloaded cast
operator, just not in C). As such, being derived from C, D's current
behavior is very logical - _far_ more so than checking the array's length.
For someone with a C/C++ background, there's no reason whatsoever to expect
that it would be checking for length. The problem comes in when you consider
that in most other cases, D tries to avoid segfaulting for null arrays, and
treats null arrays as empty (e.g. with equality), so checking for null
arrays becomes a rare thing to need, and folks from some other languages
apparently think that it's normal to expect that

if(arr)

would check for non-empty. So, it arguably becomes too confusing to allow

if(arr)

But given D's C heritage, what it currently does is exactly what I'd expect
it to do and is likely what most C/C++ programmers would expect it to do.

- Jonathan M Davis



More information about the Digitalmars-d mailing list