Switch

Rainer Deyke rainerd at eldwood.com
Mon May 18 21:36:47 PDT 2009


Andrei Alexandrescu wrote:
> Rainer Deyke wrote:
>> You're making two assumptions here:
>> 1. That inclusive ranges are preferable inside 'case' statements.
> 
> Yes. The point of case a: .. case b: is to save you from writing case a:
> case a+1: and so on up to case b:. There is no exclusion. You write now
> the cases you want to handle.
> 
>> 2. That non-inclusive ranges are preferable outside 'case' statements.
> 
> Of course. One word: STL.

I can think of two concrete advantages of half-open/non-inclusive ranges:
  1. When using zero-based indexing, '0 .. length' expresses all
elements in a sequence.
  2. A range can be 'split' on any point 'x' into subranges '0 .. x' and
'x .. length'.
Both of these advantages also apply to 'case' statements:

const int
  first_nullary_instruction = 5,
  first_unary_instruction = 5,
  first_binary_instruction = 10,
  num_instructions = 15;

switch (c) {
  case first_nullary_instruction .. first_unary_instruction:
    executeNullaryInstruction();
    break;
  case first_unary_instruction .. first_binary_instruction:
    executeUnaryInstruction();
    break;
  case first_binary_instruction .. num_instructions:
    executeUnaryInstruction();
    break;
  default:
    illegalInstruction();
    break;
}

I can think of two concrete advantages of inclusive ranges:
  1. The past-the-end element may not be known.
  2. The past-the-end element may not be representable.
Both of these advantages also outside 'case' statements:

foreach (i; 0 ... int.max) doSomethingWith(i);


-- 
Rainer Deyke - rainerd at eldwood.com



More information about the Digitalmars-d mailing list