Inappropriate usage of Essentially Character type in an addition or subtraction operation.
MISRA C 2012 Rule 10.2: Expressions of essentially character type shall not be used inappropriately in addition and subtraction operations
Category: Required
Analysis: Decidable, Single Translation Unit
Applies to: C90, C99
Amplification
The appropriate uses are:
- For the + operator, one operand shall have essentially character type and the other shall have essentially signed type or essentially unsigned type. The result of the operation has essentially character type.
- For the - operator, the first operand shall have essentially character type and the second shall have essentially signed type, essentially unsigned type or essentially character type. If both operands have essentially character type then the result has the standard type (usually int in this case) else the result has essentially character type.
Rationale
Expressions with essentially character type (character data) shall not be used arithmetically as the data does not represent numeric values.
The uses above are permitted as they allow potentially reasonable manipulation of character data. For example:
- Subtraction of two operands with essentially character type might be used to convert between digits in the range '0' to '9' and the corresponding ordinal value;
- Addition of an essentially character type and an essentially unsigned type might be used to convert an ordinal value to the corresponding digit in the range '0' to '9';
- Subtraction of an essentially unsigned type from an essentially character type might be used to convert a character from lowercase to uppercase.
Example
The following examples are compliant:
'0' + u8a /* Convert u8a to digit */
s8a + '0' /* Convert s8a to digit */
cha - '0' /* Convert cha to ordinal */
'0' - s8a /* Convert -s8a to digit */
The following examples are non-compliant:
s16a - 'a'
'0' + f32a
cha + ':'
cha - ena