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

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

RE: [avr-gcc-list] Re: Passing a string variable to lcd_puts


From: Dave Hansen
Subject: RE: [avr-gcc-list] Re: Passing a string variable to lcd_puts
Date: Mon, 30 Mar 2009 11:59:41 -0400

 From: address@hidden
[...char vs. signed cahr vs. unsigned char...]
>
> Don't look it up - if you learn the compiler's default behaviour, you
> risk writing incorrect code. If it is in any way relevant whether a
> char is signed or not, write "signed char" or "unsigned char" explicitly
> in the code. The only reason one would ever use a plain "char" is to
> hole a true character - a letter - such as in strings. Since it is (in
> general) meaningless to do arithmetic on characters, it does not matter
> if the compiler considers them to be signed or unsigned.

All true, but you need to be careful all the same.  Consider the case I ran into about 20 years ago, a custom terminal with "Function" keys (e.g., F1, F2, etc) that returned values outside the standard ASCII range (0xF1, 0xF2, etc.).
 
Consider the following code, stubbed out for illustration purposes:
 
#define EXIT_KEY 0xF1
 
extern void process_key(char key);
 
char get_key(void) {return EXIT_KEY}
 
void handle_input(void)
{
   char key;
 
   do
   {
      key = get_key();
      process_key(key);
 
   } while (key != EXIT_KEY);
}
 
In this code, the handle_input function falls into an infinite loop if plain char is signed.  This is because key gets promoted (to signed int) before the comparison  with EXIT_KEY (which is already signed int).  If plain char is signed, and key is 0xF1, the sign is extended for key, but not EXIT_KEY.
 
There are numerous solutions, but I post it here as a warning to the wise.  Sometimes math is performed on character types implicitly.
 
Regards,
 
   -=Dave
 


Express your personality in color! Preview and select themes for HotmailĀ®. See how.

reply via email to

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