For portable applications, use only the assignment =
operator, the equality operators ==
and !=
, and the unary &
operator on plain character or plain wide character-typed expressions.
This is recommended because the C99 standard requires only the digit characters ('0' - '9') to have consecutive numerical values \[[C99 N1401]\]. Thus, operations that rely on expected values for plain character or plain wide character-typed expressions can lead to unexpected behavior. |
However, due to the requirement for digit characters, other operators can be used for them according to the following restrictions:
+
operator may be used to add integer values from 0 to 9 to '0'.-
operator may be used to subtract character '0'.<
, <=
, >
, and >=
can be used to check whether a character or wide character is a digit.Character types should be chosen and used in accordance with STR04-C. Use plain char for characters in the basic character set.
The following example appears to check if the value of a character variable is between 'a'
and 'c'
inclusive. However, since the C99 standard does not require the letter characters to be consecutive or in alphabetical order, the check might not work as expected.
char ch = 'b'; if ((ch >= 'a') && (ch <= 'c')) { /* ... */ } |
In this example, the specific check is enforced using compliant operations on character expressions.
char ch = 't'; if ((ch == 'a') || (ch == 'b') || (ch == 'c')) { /* ... */ } |
STR09-EX1: It is okay to assume consecutive values for characters like a~z
on platforms where ASCII or Unicode is used. This rule is for raising awareness of platform portability, such as if the code is migrated from ASCII systems to non-ASCII systems.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
STR09-C |
low |
unlikely |
low |
P3 |
L3 |
This rule appears in the C+\+ Secure Coding Standard as \[[cplusplus:STR07-CPP. Don't assume numeric values for expressions with type plain character]\]. |
\[[C99 N1401]\] Section 5.2.1 "Character sets" |