Bizarre way to 'new' arrays

James Dunne james.jdunne at gmail.com
Fri Jun 16 07:28:08 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.
> 
> Sorry if this is a bit OT, but I thought it was interesting. 
> 
> 

There's a lot more than that in the parser code!  Start playing around 
with declarations; you can make some really scary code out of that stuff.

Some of these cases are invalidated by the semantic analyzer, while 
others pass right through.  It really depends on the specialization of 
the syntax involved.

-- 
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCS/MU/S d-pu s:+ a-->? C++++$ UL+++ P--- L+++ !E W-- N++ o? K? w--- O 
M--@ V? PS PE Y+ PGP- t+ 5 X+ !R tv-->!tv b- DI++(+) D++ G e++>e 
h>--->++ r+++ y+++
------END GEEK CODE BLOCK------

James Dunne



More information about the Digitalmars-d mailing list