comp.lang.c
[Top] [All Lists]

Re: case labels

Subject: Re: case labels
From: CBFalconer
Date: Fri, 28 Mar 2008 12:06:05 -0500
Newsgroups: comp.lang.c

user923005 wrote:
> Keith Thompson <ks...@xxxxxxx> wrote:
>> Ian Collins <ian-n...@xxxxxxxxxxx> writes:
>>> sumsin wrote:
>>>> Ian Collins <ian-n...@xxxxxxxxxxx> wrote:
>>>>> aark...@xxxxxxxxx wrote:
>>>>>>
>>>>>> why general integer expressions are not allowed in case
>>>>>> labels in switch statements..????
>>>>>
>>>>> Because they must be compile time constants.
>>>>
>>>> Could you elaborate this concept?
>>>
>>> The language requires case labels to be compile time constants. 
>>> There really isn't a concept to elaborate on.
>>
>> Unless you want to know *why* the standard imposes this
>> requirement.
>>
>> The code generated for a switch statement is typically a static
>> jump table (though it doesn't have to be).  The advantage of
>> this is that the code doesn't have to traverse through various
>> possible values of the controlling expression to determine
>> where to jump; it's typically faster than an equivalent if/else
>> chain.  The disadvantage is that the values for all the labels
>> have to be known at compile time so the compiler can construct
> the jump table.
>>
>> Having said that, there's nothing forbidding a compiler from
>> treating a switch statement like an if/else chain anyway (and
>> it will probably have to do something like that if the range
>> of cases is very large).
> 
> A smart compiler would sort the labels and do a bsearch to find
> the desired element.  Or it could compute a perfect hash at
> compile time.

Please apply that thought to 'general integer expressions'.

-- 
 [mail]: Chuck F (cbfalconer at maineline dot net) 
 [page]: <http://cbfalconer.home.att.net>
            Try the download section.


-- 
Posted via a free Usenet account from                                 www.teranews.com">http://www.teranews.com


<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy