for, foreach identifier allowed in c throws error in d

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 2 12:58:01 PDT 2014


On Mon, 02 Jun 2014 15:47:02 -0400, Logesh Pillay  
<lp.court.jester at gmail.com> wrote:

> Issue has nothing to do with recursion.  That's only where I keep seeing  
> it.
>
> eg a function to generate combinations.
>
> import std.stdio;
>
> int[3] t;
>
> void foo (int i) {
>    if (i == 3)
>      writef("%s\n", t);
>    else foreach (x; 0 .. 3) {
>      t[i] = x;
>      foo(i+1);
>    }
> }
>
> void main() {
>    foo(0);
> }
>
> In C, I could put in the equivalent for statement for foreach, t[i] as  
> the iterating variable. I won't need x which exists as a middleman only  
> and save myself two lines.

OK, I get it. You want to do:

foreach(t[i]; 0 .. 3)

But this doesn't work.

This should (the equivalent for C):

for(t[i] = 0; t[i] < 3; ++t[i])

I'm trying to think of a way to do this without loops, but not sure. Note  
that foreach is expected to be given a new variable to declare, so you  
can't foreach with an existing variable on the left.

-Steve


More information about the Digitalmars-d-learn mailing list