Thread overview
Incrementing [].length
Jun 21, 2006
Luis Marques
Jun 21, 2006
Andrei Khropov
Jun 21, 2006
jcc7
June 21, 2006
Hello

Consider this code:

int list[];
list.length += 1;

dmd issues the error "(list).length is not an lvalue".

Why doesn't "+=" work for the length property?
"list.length = list.length + 1" works.

Regards,
Luís


June 21, 2006
Luis Marques wrote:

> Hello
> 
> Consider this code:
> 
> int list[];
> list.length += 1;
> 
> dmd issues the error "(list).length is not an lvalue".
> 
> Why doesn't "+=" work for the length property?
> "list.length = list.length + 1" works.
It's because D compiler treats a = b as a(b) in order to simplify properties implementation.

So, actually
"list.length = list.length + 1;"
 equals to
"list.length( list.length() + 1 );"

As you can see "list.length += 1" doesn't fit in these semantics.

But I agree that it is some kind of inconsistency and it fools our expectations. I'd like this syntax to be allowed by some mechanism.

It has been already discussed here: http://www.digitalmars.com/drn-bin/wwwnews?digitalmars.D.learn/3516.









-- 
AKhropov
June 21, 2006
In article <e7bhde$2lli$1@digitaldaemon.com>, Luis Marques says...
>
>Hello
>
>Consider this code:
>
>int list[];
>list.length += 1;
>
>dmd issues the error "(list).length is not an lvalue".
>
>Why doesn't "+=" work for the length property?
>"list.length = list.length + 1" works.

I'm sure it's the same reason you can't use "s.length++;". ;) I think it's kind of like in Timecop when they say it'll create a paradox if the same person tries to occupy the same space twice.

Here's some expert opinions on the subject:

<quote>
It was to prevent:

array [array.length ++] = 45;

Which is dependent on undefined behaviou
</quote>
(from http://www.digitalmars.com/drn-bin/wwwnews?D/10076)


<quote>
Walter thought that
array.length++;
hid too much complexity.  That statement can cause:
* realloc
* malloc/memcpy (if realloc has to move the array)
* GC run (if malloc doesn't have space)

Personally, I wish the syntax was legal...but I don't write the compiler.
</quote>
(from http://www.digitalmars.com/drn-bin/wwwnews?D/10297)

jcc7