Why is this an issue?
There are three distinct char
types, (plain) char
, signed char
and unsigned char
. signed
char
and unsigned char
should only be used for numeric data, and plain char
should only be used for character data.
Since it is implementation-defined, the signedness of the plain char
type should not be assumed.
Noncompliant code example
signed char a = 'a'; // Noncompliant, explicitly signed
unsigned char b = '\r'; // Noncompliant, explicitly unsigned
char c = 10; // Noncompliant
unsigned char d = c; // Noncompliant, d is explicitly signed while c is not
char e = a; // Noncompliant, a is explicitly signed while e is not
Compliant solution
char a = 'a';
char b = '\r';
unsigned char c = 10;
signed char c = 10;
Exceptions
- Since the integer value 0 is used as a sentinel for the end of a string, converting this value to char is ignored.
Resources
- MISRA C:2004, 6.1 - The plain char type shall be used only for the storage and use of character values
- MISRA C:2004, 6.2 - signed and unsigned char type shall be used only for the storage and use of number values
- MISRA C++:2008, 5-0-11 - The plain char type shall only be used for the storage and use of character values
- MISRA C++:2008, 5-0-12 - signed char and unsigned char type shall only be used for the storage and use of numeric values
- CERT, INT07-C. - Use only explicitly signed or unsigned char type for numeric values
- CERT, STR00-C. - Represent characters using an appropriate type
- CERT, STR04-C. - Use plain char for characters in the basic character set