The three types char
, signed char
, and unsigned char
are collectively called the character types. Compilers have the latitude to define char
to have the same range, representation, and behavior as either signed char
or unsigned char
. Irrespective of the choice made, char
is a separate type from the other two and is not compatible with either.
Use only signed char
and unsigned char
types for the storage and use of numeric values , as this is because it is the only portable way to guarantee the signedness of the character types. See recommendation STR00-C. Represent characters using an appropriate type for more information on representing characters.
...
Code Block | ||||
---|---|---|---|---|
| ||||
char c = 200;
int i = 1000;
printf("i/c = %d\n", i/c);
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned char c = 200;
int i = 1000;
printf("i/c = %d\n", i/c);
|
Exceptions
INT07-EX1: Rule FIO34-C. Use int to capture the return value of character IO functions mentions that certain character IO functions return a value of type int
. Despite being returned in an arithmetic type, the value is not actually numeric in nature, so it is acceptable to later store the result into a variable of type char
.
...
Tool | Version | Checker | Description | section||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
| 93 S | Fully Implemented sectionimplemented. | |||||||||
Fortify SCA | Section | V. 5.0 |
| Section | Can detect violations of this recommendation with the CERT C Rule Pack. section | ||||||
Splint |
|
| section | ||||||||
Compass/ROSE |
| section | Can detect violations of this recommendation. In particular, it flags any instance of a variable of type | ||||||||
| Section | charplan Section | | Fully Implementedimplemented. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: INT07-CPP. Use only explicitly signed or unsigned char type for numeric values
ISO/IEC 9899:19992011 Section 6.2.5, "Types"
ISO/IEC TR 24772 "STR Bit Representationsrepresentations"
MISRA Rule 6.2, "Signed and unsigned char type shall be used only for the storage and use of numeric values"
MITRE CWE: CWE-682, "Incorrect Calculationcalculation"
Bibliography
...