avr-gcc-list
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: [avr-gcc-list] Inconsisten behaviour of switch statement


From: Eric Weddington
Subject: RE: [avr-gcc-list] Inconsisten behaviour of switch statement
Date: Mon, 26 Mar 2007 07:40:56 -0600

 

> -----Original Message-----
> From: Schwichtenberg, Knut [mailto:address@hidden 
> Sent: Monday, March 26, 2007 7:34 AM
> To: Eric Weddington; address@hidden
> Subject: RE: [avr-gcc-list] Inconsisten behaviour of switch statement
> 
> Hi, 
> 
> > -----Original Message-----
> > From: Eric Weddington [mailto:address@hidden 
> > Sent: Monday, March 26, 2007 2:46 PM
> > To: Schwichtenberg, Knut; address@hidden
> > Subject: RE: [avr-gcc-list] Inconsisten behaviour of switch 
> statement
> > 
> > The compiler has heuristics that decide when to compile a 
> > switch statement
> > into an if-else-if structure, or as a table jump. If you do 
> > not like the
> > output that it produces, it would be better if you coded your 
> > algorithm as a
> > dispatch table (array of pointers to functions). This gives 
> > you more control
> > as to how the compiler will transform the C into assembly.
> 
> Eric, the point is not that I don't like the output, but the 
> case to be
> selected should be deterministic. I always thought that a switch
> statement would lead to identical results if the input value is
> identical. This is currently not true. The table jump for a volatile
> variable is identical to an if-then-else structure of a non-volatile
> variable and the current if-then-else implementation for a volatile
> variable can not be simulated by a table jump.

This is one of many reasons why I personally don't like switch statements in
embedded code. I still suggest coding your algorithm as a dispatch table.
Give it a try.


> 
> > Have you tried typecasting all of the case
> > integer constants to uint8_t? Perhaps that will have the 
> > desired effect.
> Not yet, I've tried to typecast the switch-Variable, but that did not
> help. Therefore I'll try your idea.

Typecasting the switch variable won't do any good as the variable is already
declared as an uint8_t. It's the constants that need typecasting, otherwise
the compiler promotes the other operand (the variable) to int.

HTH
Eric





reply via email to

[Prev in Thread] Current Thread [Next in Thread]