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

Re: case labels

Subject: Re: case labels
From: user923005
Date: Thu, 27 Mar 2008 23:59:17 -0700 PDT
Newsgroups: comp.lang.c

On Mar 27, 11:33 pm, Keith Thompson <ks...@xxxxxxx> wrote:
> Ian Collins <ian-n...@xxxxxxxxxxx> writes:
> > sumsin wrote:
> >> On Mar 28, 10:03 am, Ian Collins <ian-n...@xxxxxxxxxxx> wrote:
> >>> aark...@xxxxxxxxx wrote:
> >>>> Hi,
> >>>> why general integer expressions are not allowed in case labels in
> >>>> switch statements..????
> >>> Because they must be compile time constants.
>
> > *Please* don't quote signatures.
>
> >> 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.

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