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

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

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


From: David Brown
Subject: [avr-gcc-list] Re: Passing a string variable to lcd_puts
Date: Mon, 30 Mar 2009 22:09:20 +0200
User-agent: Thunderbird 2.0.0.21 (Windows/20090302)

Dave Hansen wrote:
 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

That's a very helpful warning!

It's also a good reason for using the -Wconversion flag (which gives the warning "warning: conversion to 'char' alters 'int' constant value"), and -Wextra (which gives "warning: comparison is always true due to limited range of data type").

Warnings are very useful, whether given by the compiler or given by humans.

mvh.,

David





reply via email to

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