Switch: Case Range Syntax

Timon Gehr timon.gehr at gmx.ch
Wed Aug 17 11:05:19 PDT 2011


On 08/17/2011 07:27 PM, Vijay Nayar wrote:
> D adds a very handy feature that allows you to check for a range of
> values in a single case.  Is there a particular reason that the syntax
> "case<start>:  .. case<end>:" is used instead of treating the case
> statement similarly to an array slice, e.g. "case<start>  ..<end>:"?
>
> For example:
>
> import std.stdio;
>
> void main() {
>      int bob = 12;
>      switch (bob) {
>          // Why not "case 0 .. 9:"?
>          case 0: .. case 9:
>              writeln("Less than 10.");
>          case 10: .. case 19:
>              writeln("Less than 20.");
>          case 20: .. case 29:
>              writeln("Less than 30.");
>              break;
>          default:
>              break;
>      }
>      // Output:  Less than 20.  Less than 30.
> }
>
>   - Vijay

With the other syntax, the wrapping switch statement really should look 
like this:

switch(a .. b){
     case x .. y:       // a case statement that matches a range
}

as opposed to:

switch(a){
     case x: .. case y: // a range of case statements
}





More information about the Digitalmars-d mailing list