For portable applications, use only the assignment =
operator, the equality operators ==
and !=
, and the unary &
operator on plain character character–typed or plain wide character-typed character–typed expressions.
This is recommended because the C99 C standard requires only the digit characters ('0' - '9'0–9) to have consecutive numerical values. Consequently, operations that rely on expected values for plain character character– or plain wide character-typed character–typed expressions can lead to unexpected behavior.
...
- The binary
+
operator may be used to add integer values from 0 to 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.
Character types should be chosen and used in accordance with recommendation STR04-C. Use plain char for characters in the basic character set.
...
This noncompliant code example attempts to determine if the value of a character variable is between 'a'
and 'c'
inclusive. However, because the C99 C standard does not require the letter characters to be consecutive or in alphabetical order, the check might not work as expected.
Code Block | ||||
---|---|---|---|---|
| ||||
char ch = 'b';
if ((ch >= 'a') && (ch <= 'c')) {
/* ... */
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
char ch = 't';
if ((ch == 'a') || (ch == 'b') || (ch == 'c')) {
/* ... */
}
|
...