Bizarre way to 'new' arrays

Sean Kelly sean at f4.ca
Thu Jun 15 20:18:38 PDT 2006


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



More information about the Digitalmars-d mailing list