On Mon, 14 May 2012 06:08:17 -0400, Gor Gyolchanyan
<[email protected]> wrote:
Hi! I have a small question:
Is the test for a null array equivalent to a test for zero-length array?
== tests for length and content equivalence.
'is' tests for both pointer and length equivalence (and therefore, content
equality is implied).
There is a large confusion with null arrays. A null array is simply an
empty array that happens to be pointing to null. Other than that, it is
equivalent to an empty array, and should be treated as such.
One can use the idea that "null arrays are special", but it leads to
likely confusing semantics, where an empty array is different from a null
array. if(arr) should IMO succeed iff length > 0. That is one of the
main reasons of the confusion.
Note that [] is a request to the runtime to build an empty array. The
runtime detects this, and rather than consuming a heap allocation to build
nothing, it simply returns a null-pointed array. This is 100% the right
decision, and I don't think anyone would ever convince me (or Andrei or
Walter) otherwise.
This is particularly interesting for strings.
For instance, I could return an empty string from a toString-like
function
and the empty string would be printed, but If I returned a null string,
that would indicate, that there is no string representation and it would
cause some default string to be printed.
These are the confusing semantics I was referring to ;) I would recommend
we try to avoid this kind of distinction wherever possible.
So, the question is, if a null array is any different from an empty
array?
I would say it technically is different, but you should treat it as
equivalent unless you have a really really good reason not to. It's just
another empty array which happens to be pointing at 0.
-Steve