Forbid dynamic arrays in boolean evaluation contexts
Steven Schveighoffer
schveiguy at yahoo.com
Mon Mar 25 07:46:27 PDT 2013
On Mon, 25 Mar 2013 10:18:11 -0400, Daniel Murphy
<yebblies at nospamgmail.com> wrote:
> "bearophile" <bearophileHUGS at lycos.com> wrote in message
> news:bwgnbflygowctlisistg at forum.dlang.org...
>> 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:
>
> I am in favour of deprecating/removing this, then bringing it back so
> that
> if (arr)
> is the same as
> if (arr.length)
I would favor just changing the behavior. The existing behavior is most
often a bug when it is used, because quite often arrays are null (that is
the default value), and quite often, people THINK they are checking if the
array is empty instead of if the pointer is null. Because most empty
arrays are null, and null arrays have zero length, their tests do not
expose this bug. It's actually very difficult to generate a non-null
empty array for testing. [] does not work, it returns a null array!
Only in rare cases do people actually want to check for null, and in most
people's code it is an error when a non-null but empty array is checked
with if(arr). If people are interested in the pointer, they usually check
if(arr.ptr) or if(arr !is null).
I would posit that for every knowledgeable person who uses this "shortcut"
to check for null, 100 people use it expecting it to be measuring the
array length.
If we go through a deprecation cycle, it makes people who do if(arr) for
length have to change there code to if(arr.length) then back to if(arr)
once the deprecation is over. The switch to if(arr.length) will be
simple, the compiler will show all the places if(arr) is used, but the
switch back will be more difficult since if(arr.length) will not be
deprecated.
What about a switch that identifies all places where if(arr) is done?
Then people who use if(arr) for testing if(arr.ptr) can find and fix their
cases. Or even a separate tool to do that.
-Steve
More information about the Digitalmars-d
mailing list