switch case for constants-only?

Nick Sabalausky a at a.a
Sat Dec 5 19:05:38 PST 2009


"BCS" <none at anon.com> wrote in message 
news:a6268ffdcc98cc43ebb9955246 at news.digitalmars.com...
> Hello Nick,
>
>> "BCS" <none at anon.com> wrote in message
>> news:a6268ffdcb78cc43db75126b3c at news.digitalmars.com...
>>
>>> Just jumping a ways down this rabbit hole...
>>>
>>> struct S { int i; int opCmp(S s) { return i-- == s.i++; }
>>>
>>> {
>>> S a,b,c,d,e; ...
>>> switch(a)
>>> {
>>> case b: break;
>>> case c: break;
>>> case d: break;
>>> case e: break;
>>> }
>>> }
>>> Oh, boy. What the hack does the above do?
>>>
>> It blatantly abuses operator overloading ;)  Start doing stuff like
>> that, and you'll wind up in wonderland even without changing switch.
>>
>
> Ok then how about:
>
>
> switch(c)
> {
>    case getc(): ..... break;
>    case getc(): ..... break;
>    case getc(): ..... break;
>    case getc(): ..... break;
>    case getc(): ..... break;
>    case getc(): ..... break;
>    case getc(): ..... break;
> }
>
>

I think we can reasonably expect run-time-value cases to be checked in order 
(or at least whenever the optimizer can't guarantee that it won't matter), 
so that then becomes pretty simple: If the nth character the user enters (up 
to the number of cases) matches c, then the nth case is executed, and only 
the first match is used. I'm not sure it would make much sense to use every 
match. Switch is a selector, not a multiplexer.

> Are you only going to allow pure functions and expressions with no side 
> effects?

That could be worth exploring. But for now, I'd say no.

> I'd guess you could try and set down the list of rules that makes this 
> sane but it's not something I'd like to try any time soon.
>

The rule is simple: Just translate it to an if-else chain.





More information about the Digitalmars-d mailing list