"bearophile" <bearophileh...@lycos.com> wrote in message news:ibn320$2uc...@digitalmars.com... > In a not-ranged cases body, like in the program below (that doesn't > compile), the switch variable is a compile-time constant, so why doesn't > the compile see x as constant there?
In switch statements, you can do stuff like: switch(x) { case 0: case 1: // what is x here? break; } switch(x) { case 0: break; // what is x here? case 1: goto case 0: } goto label1; switch(x) { case 0: label1: break; // what is x here? } switch(x) { case 0: x = y; break; // what is x here? } As far as I know, NONE of the constructs in d allow you to treat a run-time variable as if it was compile-time constant. I doubt this would be possible without flow analysis. You can however do something like this (if you must) template Foo(uint x) { static if (x <= 1) enum Foo = 1; else enum Foo = x * Foo!(x - 1); } int getv(int x) { switch(x) { foreach(i; TypeTuple!(0, 1, 2, 3, 4, 5, 6)) { case i: return Foo!i; } } assert(0); } where the switch expands out to switch(x) { case 0: return Foo!0; case 1: return Foo!1; case 2: return Foo!2; case 3: return Foo!3; case 4: return Foo!4; case 5: return Foo!5; case 6: return Foo!6; } Is this DRY enough for you?