For portable applications, use only the assignment =
operator, the equality operators ==
and !=
, and the unary &
operator on plain character–typed -character-typed or plain-wide-character-character–typed typed expressions.
This is practice is recommended because the C standard Standard requires only the digit characters (0–9) to have consecutive numerical values. Consequently, operations that rely on expected values for plain character– -character- or plain-wide-character-character–typed typed expressions can lead to unexpected behavior.
...
- The binary
+
operator may be used to add integer values 0 through 9 to'0'
. - The binary
-
operator may be used to subtract character 0. - Relational operators
<
,<=
,>
, and>=
can be used to check whether a character or wide character is a digit.
...
This noncompliant code example attempts to determine if the value of a character variable is between 'a'
and 'c'
inclusive. However, because the C standard Standard does not require the letter characters to be in consecutive or in alphabetical or alphabetic order, the check might not work as expected.
...
In this example, the specific check is enforced using compliant operations on character expressions.:
Code Block | ||||
---|---|---|---|---|
| ||||
char ch = 't'; if ((ch == 'a') || (ch == 'b') || (ch == 'c')) { /* ... */ } |
Exceptions
STR09-EX0C-EX1: Consecutive values for characters like a~z
can be assumed on platforms where ASCII or Unicode is used. This recommendation is primarily concerned with platform portability, for example, if code is migrated from ASCII systems to non-ASCII systems.
Risk Assessment
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
STR09-C |
Low |
Unlikely |
Low | P3 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
Astrée |
| Supported indirectly via MISRA C:2012 rule 10.1. | |||||||
Axivion Bauhaus Suite |
| CertC-STR09 | |||||||
Helix QAC |
| C2106, C2107 | |||||||
LDRA tool suite |
| 329 S | Fully implemented | ||||||
Parasoft C/C++test |
| CERT_C-STR09-a | Expressions with type (plain) char and wchar_t shall not be used as operands to built-in operators other than =, ==, != and the unary & operator | ||||||
PC-lint Plus |
| 9209 | Fully supported | ||||||
RuleChecker |
| Supported indirectly via MISRA C:2012 rule 10.1. |
Related Guidelines
...
...
Bibliography
[Jones 2009] | Section 5.2.1, "Character |
...
Sets" |
...