Switch: Case Range Syntax

Don nospam at nospam.com
Thu Aug 18 22:07:55 PDT 2011


Vijay Nayar wrote:
> 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?

Yes. That's why the maximum length of the range is currently limited to 
256 cases. Something like:
case 0: .. case int.max: break;
won't currently compile.


More information about the Digitalmars-d mailing list