The following MISRA violations appeared while analyzing the following code:
#define z (USHORT)14745
#define Convert(x) ((((USHORT)x*(unsigned short)1000) + ((z) / (USHORT)2)) /(z))
static const USHORT array [2] =
{
Convert(176), -> Line "1"
Convert(206) -> Line "2"
};
The following MISRA violations are detected on both lines "1", "2":
Integral promotion : unsigned short promoted to unsigned int. REFERENCE - ISO:C90-6.2.1.1 Characters and Integers
Constant: Wraparound in unsigned arithmetic operation. MISRA-C:2004 Rule 12.11; REFERENCE - ISO:C90-6.1.2.5 Types
The result of this cast is implicitly converted to another type.
My question is: Why there will be a wraparound in this operation ?!
Note: When I am checking the values of array
with debugger:
array [2] =
{
12,
14
}
which are the correct values.
It is related to Integral Promotion:
Integer types smaller than int are promoted when an operation is performed on them. If all values of the original type can be represented as an int, the value of the smaller type is converted to an int; otherwise, it is converted to an unsigned int.
So that, the macro Convert(206) [((((unsigned short)206*(unsigned short)1000) + ((z) / (USHORT)2)) /(z))]
will be executed as following: