Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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 C++ standard requires only the digit characters ('0' - '9') to have consecutive numerical values. 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, the usage of other operators is allowed for them according to the following restrictions:

  • The binary + operator may be used to add integer values from 0 to 9 to '0'.
  • The binary - operator may be used to subtract character '0'.
  • Relational operators <, <=, >, >= may 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.

Noncompliant code example

The following example would seem to check if the value of a character variable is between 'a' and 'c' inclusive. However, since it is not required that the letter characters be consecutive nor in alphabetical order, the check might not work as expected.

Code Block
bgColor#FFCCCC
char ch = 'b';
if ( ( ch >= 'a' ) && (ch <= 'c') ){
...
}

Compliant code example

In this example, the specific check is enforced using compliant operations on character expressions.

Code Block
bgColor#CCCCFF
char ch = 't';
if ( ( ch == 'a' ) || ( ch == 'b') || ( ch == 'c') ){
...
}

Risk assesment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

STR09-C

low

unlikely

low

P3

L3

Other Languages

This rule appears in the C++ Secure Coding Standard as STR07-CPP. Don't assume numeric values for expressions with type plain character.

References

Wiki Markup
\[[WG14 N1124|http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf]\] Section 5.2.1 "Character sets"