Switch: Case Range Syntax

Vijay Nayar madric at gmail.com
Thu Aug 18 08:02:54 PDT 2011


On Wed, 17 Aug 2011 17:51:48 -0500, Andrei Alexandrescu wrote:

> 
> I doubt that would work well. Let's ignore for now mundane issues such
> as the ambiguity of 3...5 and focus on something like:
> 
> int x;
> ...
> switch (x) {
> case 3 ... 5: return 1;
> default: return 0;
> }
> 
> We'd need to change the behavior of switch anyway, or we'd need to
> define equality such that e.g. 4 == 3 ... 5. But then equality is not
> transitive anymore because 4 == 2 ... 6 too, but 3 ... 5 is not equal to
> 2 ... 6.
> 
> Adding new built-in types is not easy. For a variety of reasons we
> should move the other way (per e.g. the hashtables discussion
> elsethread).
> 
> 
> Andrei

>From this discussion, I gather that the 'switch' statement is effectively 
using '==' to compare to each 'case' statement value (I didn't know 
that's how it worked).

Andrei, you are very good at explaining concepts in plain English, and I 
was hoping you could explain what D is seeing when it sees the 'case 
A: .. case B:' syntax.

My current understanding is that 'switch' is effectively iterating 
through all it's top-level tokens, which are 'case', '..', and 'default', 
in a manner similar to a for-loop.  The special top-level token '..' is 
interpreted to effectively turn into new 'case' tokens starting from the 
last seen 'case' and ending when the next 'case' is seen.

Is that correct?  Does the D 'switch' statement replace the '..' token 
with a bunch of 'case' tokens, thus allowing the 'swtich' hash-lookup to 
work quickly and efficiently?

 - Vijay


More information about the Digitalmars-d mailing list