Switch Statement case '0': .. case '9'

Timon Gehr timon.gehr at gmx.ch
Thu Jun 14 09:16:18 PDT 2012


On 06/14/2012 05:59 PM, Paul wrote:
> The book in section 3.5 gives these valid case examples:
>
> case ’0’: .. case ’9’:
> case ’A’: .. case ’Z’: case ’a’: .. case ’z’:
> case ’.’, ’,’, ’:’, ’;’, ’!’, ’?’:
>
> In my code:
>
> case "STEP01": ...compiles and works correct
> case "STEP01", "STEP02": ...compiles and works correct
> case "STEP01": .. case "STEP50": ...compiler reports:
>
> iccstats.d(27): Error: Integer constant expression expected instead of
> "STEP01"
> iccstats.d(27): Error: Integer constant expression expected instead of
> "STEP50"
> iccstats.d(27): Error: integral constant must be scalar type, not
> const(char[])
>
> Help please.

case-range expressions don't work with strings. (because there is no 
general way to meaningfully fill in the gap.)

You could automatically generate the case statements via a string mixin 
(untested):

mixin({
     string r;
     foreach(i;1..51) r~=`case "STEP`~(i<10?"0":"")~to!string(i)~`":`;
     return r;
}());

But that is probably overkill, why not just parse the string with an if 
statement?

If you need fallthrough, you can use a goto statement

if(...) goto Lstepn;
switch(...){
     case ...:
         ...
         break;
     Lstepn:
     case ...:
         ...
         break;
}


More information about the Digitalmars-d-learn mailing list