null Vs [] return arrays
Jonathan M Davis
jmdavisProg at gmx.com
Sun Mar 27 14:11:27 PDT 2011
On 2011-03-27 11:42, bearophile wrote:
> Kagamin:
> > [] is not null, it's an array of 0 elements, what is done exactly.
> > edx points to the allocated array.
>
> I don't understand what you say. I think the caller of foo() and bar()
> receive the same thing, two empty registers. I think that cast(int[])null
> and cast(int[])[] are the same thing for D.
>
> void main() {
> assert(cast(int[])null == cast(int[])null);
> auto a1 = cast(int[])null;
> a1 ~= 1;
> auto a2 = 1 ~ cast(int[])null;
> }
What I would _expect_ the difference between a null array and an empty one to
be would be that the null one's ptr property would be null, whereas the empty
one wouldn't be. But dmd treats them pretty much the same. empty returns true
for both. You can append to both. The null one would be a guaranteed memory
reallocation when you append to it whereas the empty one may not be, but their
behavior is almost identical.
How that affects the generated assembly code, I don't know. Particularly if
you're compiling with -inline and and -O, the compiler can likely make
assumptions about null that it can't make about [], since it probably treats
[] more generally without worrying about the fact that it happens to be empty
as far as optimizations go - that and there _is_ a semantic difference between
null and [] if you're messing with the ptr property, so Walter may think that
it's best for null to not be turned into the same thing as [] automatically.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list