Does foreach on array literal allocate?

Bill Baxter wbaxter at
Thu Dec 4 18:35:50 PST 2008

On Fri, Dec 5, 2008 at 10:37 AM, Walter Bright
<newshound1 at> wrote:
> Bill Baxter wrote:
>> Does anyone know off the top of their head if code like this allocates
>> or not with current DMD 1.x compilers?
>> foreach(x; [1, 2, 3, 4])
>> {
>>     // do something non-allocating with x
>> }
> Here's how to find out. Compile:

Thanks for the explanation.  Though Obj2Asm is I think part of the EUP, right?
Maybe I'll get that after all.

> and note the call to gc_malloc().


Does a static-sized array initializer also allocate?

int[4] v = [1,2,3,4];
foreach(x; v) {
    /// ...

Or maybe this (also) works without allocation?

foreach(x; Tuple!(1,2,3,4))

This kinda code is useful for the case where you have to do the same
thing to two or three local variables.  You can write a local function
to do it, but foreach on a static set of them breaks up the visual
flow of the code a little less, I think.


More information about the Digitalmars-d mailing list