Switch constants

Daniel Murphy yebblies at nospamgmail.com
Sat Nov 13 16:15:11 PST 2010


"bearophile" <bearophileHUGS at lycos.com> wrote in message 
news:ibn320$2ucs$1 at 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? 




More information about the Digitalmars-d-learn mailing list