Bizarre way to 'new' arrays
Gregor Richards
Richards at codu.org
Thu Jun 15 23:56:35 PDT 2006
Sean Kelly wrote:
> Jarrett Billingsley wrote:
>
>> I was looking through parse.c again, and in the ::parseNewExp()
>> function, I noticed something odd. Interested, I typed this in:
>>
>> int[] x = new int[](4);
>>
>> And it compiles and runs. Writing
>>
>> writefln(x.length);
>>
>> displays 4.
>>
>> This is legal because a NewExpression can be defined as
>>
>> 'new' [(ArgumentList)] Type (ArgumentList)
>>
>> So in the case of 'new int[](4)', int[] is parsed as the Type and the
>> (4) is parsed as the argument list. In fact, writing 'new int[4]' is
>> just syntactic sugar for 'new int[](4)'. This makes sense, as when
>> you new an array (or anything for that matter), you're really calling
>> a function.
>
>
> Sadly, this isn't legal:
>
> int* i = new int(5);
>
> To allocate and initialize an integer. AFAIK there's no way around
> having the assignment as a separate statement following the allocation.
>
>
> Sean
int* i = (new int[5]).ptr;
- Gregor Richards
More information about the Digitalmars-d
mailing list