switch case for constants-only?

Nick Sabalausky a at a.a
Sat Dec 5 16:45:55 PST 2009


"Sean Kelly" <sean at invisibleduck.org> wrote in message 
news:hfeqbg$143u$1 at digitalmars.com...
> Nick Sabalausky Wrote:
>
>> "Sean Kelly" <sean at invisibleduck.org> wrote in message
>> news:hfelka$rhf$1 at digitalmars.com...
>> > Nick Sabalausky Wrote:
>> >
>> >> I just noticed in D1 that the values for the cases in a switch must be
>> >> known
>> >> at compile-time (btw, the docs don't seem somewhat vague on that). Is
>> >> this
>> >> also true in D2? If so, I don't suppose we could get that changed 
>> >> before
>> >> the
>> >> book? It's a real PITA for dynamic code.
>> >
>> > int x = 1, y = 1;
>> >
>> > switch( z )
>> > {
>> > case x:
>> >    ...
>> > case y:
>> >    ...
>> > }
>> >
>> > What should this do?  Throw an exception perhaps?
>>
>> As I mentioned earlier, that should be semantically equivilent to:
>>
>> int x = 1, y = 1;
>>
>> if(z == x)
>> { ... }
>> else if(z == y)
>> { ... }
>>
>> In fact, it's already semantically equivilent to that, except that x and 
>> y
>> are currently required to be known at compile-time.
>
> D allows duplicate case values?  I thought this was a compile error.

I slightly mis-spoke. I meant if you take a current valid switch statement, 
then that switch statement is semantically equivilent to the above pattern, 
and if you take something in the patten above that fits switch's current 
"unique and known at compile-time" restrictions, then that's equivilant to a 
certain switch statement.

I guess what I was really saying is that the "unique" requirement makes 
sense when the values are all known at compile-time, because it's amounts to 
this...

if(z == 1)
{ ... }
else if(z == 1)
{ /+ dead code +/ }

...but when they're not known at compile-time, that reasoning (along with 
the resulting restriction) is no longer applicable. Note though, that I'm 
not necissarily advocating the removal of that restriction from 
known-at-compile-time values, just for values known only at runtime.





More information about the Digitalmars-d mailing list