switch

Nobody nobody at nowhere.com
Thu Dec 10 13:16:44 EST 2009


On Thu, 10 Dec 2009 05:47:19 +0000, Steven D'Aprano wrote:

>>> I string together a bunch of elif statements to simulate a switch
>>> 
>>> if foo == True:
>>> 	blah
>>> elif bar == True:
>>> 	blah blah
>>> elif bar == False:
>>> 	blarg
>>> elif ....
>> 
>> This isn't what would normally be considered a switch (i.e. what C
>> considers a switch). 
> 
> Anyone would think that C was the only programming language in 
> existence...

It's the only one I know of which calls such statements "switch"
statements. Most other languages call them "case" statements.

>> A switch tests the value of an expression against a
>> set of constants.
> 
> In C. Things may be different in other languages.
> 
> For example, I recall the so-called "4GL" (remember when that was the 
> marketing term of choice for interpreted programming languages?) 
> Hyperscript from Informix. I can't check the exact syntax right now, but 
> it had a switch statement which allowed you to do either C-like tests 
> against a single expression, or if-like multiple independent tests.

Interpreted languages generally don't care about the labels being
constant, so you can do e.g. (BBC BASIC V):

	CASE TRUE OF
	WHEN foo: blah
	WHEN bar: blah blah
	WHEN NOT(bar): blarg
	ENDCASE

The test expression is compared against each case expression sequentially
until one matches; both the test expression and case expressions are
evaluated at run-time.

This is essentially just an if/elif chain with different syntax,
whereas a C-style switch may be signficiantly more efficient (e.g. using a
jump table or a balanced tree).

>> Compiled languages' switch statements typically require constant labels
>> as this enables various optimisations.
> 
> Pascal, for example, can test against either single values, enumerated 
> values, or a range of values:
> 
> case n of
>    0:
>      writeln('zero');
>    1, 2:
>      writeln('one or two');
>    3...10:
>      writeln('something between three and ten'); 
>    else writeln('something different'); 
>  end;

IOW, identical semantics to C, but with some extra syntax to avoid the
need to write multiple consecutive labels.




More information about the Python-list mailing list