Main Content

MISRA C++:2008 Rule 5-0-12

Signed char and unsigned char type shall only be used for the storage and use of numeric values

Description

Rule Definition

Signed char and unsigned char type shall only be used for the storage and use of numeric values.

Rationale

In C/C++, there are three types of char:

  • Plain char

  • signed char

  • unsigned char

The signedness of plain char is implementation-defined. Plain char cannot be interchangeably used with the other types. For instance, you might assume char is unsigned and use unsigned char to store character. Your implementation might interpret characters as signed. In such a situation, your code might behave in unexpected manner, leading to bugs that are difficult to diagnose.

MISRA C++:2008 limits the use of these three types of char for different applications. The signed and unsigned char type is appropriate for numeric values and storage. The plain char is appropriate for character data. Avoid using signed or unsigned char when you intend to use the plain char.

This rule also applies to the different typedef of these char types, such as uint8_t and int8_t. See MISRA C++:2008 Rule 3-9-2.

Polyspace Implementation

Polyspace® raises a violation of this rule when a plain char is implicitly converted to either signed char or unsigned char.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

typedef signed   char         int8_t;
typedef unsigned char         uint8_t;

namespace foo
{
	int8_t        ch_1   =   'a';     // Noncompliant
	uint8_t       ch_2  =   '\r';     // Noncompliant
	char          ch_3  =   'A';      // Compliant
	int8_t        num_1   =   10;     // Compliant
	uint8_t       num_2   =   12U;    // Compliant
	signed char   num_3   =   11;     // Compliant 

};

In this example, Polyspace flags the use of signed char and unsigned char to store character data. The character literals are of plain char types, and Polyspace flags the implicit conversion of these plain char types to explicitly signed or unsigned char types.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2015a