array.length++ not an lvalue
Koroskin Denis
2korden at gmail.com
Wed Jun 18 07:30:39 PDT 2008
On Wed, 18 Jun 2008 17:12:19 +0400, Erik Lechak <prochak at netzero.net>
wrote:
> Hello all,
>
> I just wanted to start by thanking you for the great responses to my
> previous questions. I appreciate the knowledgeable and friendly nature
> of this newsgroup.
>
> I ran into my first WTF moment with D. I spent way too much time
> figuring out why 'array'.length++ was a compiler error (Error: x.length
> is not an lvalue).
>
> This is a newsgroup entry describing the problem:
> http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=39179
>
> Is there a document detailing these "special exceptions" so that I don't
> have to blindly stumble upon them? If not are there any more that
> should be documented so that I can add them to my Wiki
> (http://www.lechak.info/wiki/index.php?title=D_Programming_Language)?
>
> For what it's worth, I think 'array'.length++ and 'array'.length += 1
> should be valid. If that is not an option, it would be nice if the
> error message could be changed to something like "Error: x.length is a
> special property that prohibits the use of the increment (++) and
> add_and_assign (+=) operators".
>
> Thanks,
> Erik Lechak
>
Length property of the array is not a member variable, but rather a member
function:
int[] array = new int[42];
assert(array.length() == 42);
but you can also omit paranthesis (that's merely a syntax sugar):
assert(array.length == 42);
The same way the following:
array.length = 100
is translated into a function call: array.length(100); which does array
resizing.
Note that you should normally call array.length(array.length() + 1) (or
array.length = array.length + 1) in order to increase array size by 1,
and what you write is this:
array.length() += 1;
array.length()++;
It doesn't make much sense, since you increment a temporary variable!
D *could* do the following trick:
array.length()+=1 -> array.length(array.length() + 1);
but it would break too much of the existing code and makes a little of
sense.
Other solution would be to return some object that would behave like int
(be opImplicitCast'able to it) and have an overloaded opAssign,
opAddAssign, etc, but does anybody *really* interested in it?
P.S. I just checked and it appears that you don't have an option of having
paranthesis, unlike usual member functions, i.e. the following is not
semantically correct (although it ought to be, IMO):
// trying to resize an array
array.length(42); // error, use array.length = 42 instead.
But the logic is the same. Please, correct me if I'm wrong.
More information about the Digitalmars-d
mailing list