Switch: Case Range Syntax

Jonathan M Davis jmdavisProg at gmx.com
Wed Aug 17 13:00:33 PDT 2011


On Wednesday, August 17, 2011 12:35 Jacob Carlborg wrote:
> On 2011-08-17 19:48, Jonathan M Davis wrote:
> > On Wednesday, August 17, 2011 10:27 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.
> >> }
> > 
> > I don't know, but ranged case statements don't have the same semantics as
> > giving a range of values when slicing or to a foreach loop, so that may
> > be why.
> > 
> > arr[0 .. 10]
> > 
> > does _not_ include the element at index 10.
> > 
> > case 0: case 10:
> > 
> > _does_ include 10. So, it actually probably be a bad thing for them to
> > use the same syntax. To use the same syntax for both would make the
> > semantics of that syntax inconsistent and confusing.
> > 
> > - Jonathan M Davis
> 
> D should have a built-in range type. One that supports syntax for both
> including and excluding the last element:
> 
> auto a = 3 .. 5
> auto b = 3 ... 5
> 
> Then we wouldn't need a special range syntax for switch statements. You
> could store ranges in variables and pass them to functions. opSlice
> probably wouldn't be needed, instead opIndex could be used and you would
> declare the method to take a range instead of two integers.

I suggest that you read the thread that Lars linked to. That type of syntax 
got shot down essentially for being too easy to confuse .. with ... making it 
hard to read and easy to screw-up. Regardless, the whole issue got discussed 
ad naseum there, and the situation definitely isn't going to change for D2, so 
there really isn't much point in arguing the pros and cons at this point.
Maybe there will be something similar in D3 if someone can find an
appropriately clear syntax for it, but I'd be very surprised if any such thing
happened in D2.

- Jonathan M Davis


More information about the Digitalmars-d mailing list