MISRA.ETYPE.COMP.CAST.EXPL.DIFFERENT.2012MISRA C 2012 Rule 10.8: The value of a composite expression shall not be cast to a different essential type category or a wider essential typeCategory: Required Analysis: Decidable, Single Translation Unit Applies to: C90, C99 RationaleThe rationale is described in the introduction on composite operators and expressions (see Section 8.10.3). Casting to a wider type is not permitted as the result may vary between implementations. Consider the following:
( uint32_t ) ( u16a + u16b ); On a 16-bit machine the addition will be performed in 16 bits with the result wrapping modulo-2 before it is cast to 32 bits. However, on a 32-bit machine the addition will take place in 32 bits and would preserve high-order bits that would have been lost on a 16-bit machine. Casting to a narrower type with the same essential type category is acceptable as the explicit truncation of the result always leads to the same loss of information. Example( uint16_t ) ( u32a + u32b ) /* Compliant */ ( uint16_t ) ( s32a + s32b ) /* Non-compliant - different essential * type category */ ( uint16_t ) s32a /* Compliant - s32a is not composite */ ( uint32_t ) ( u16a + u16b ) /* Non-compliant - cast to wider * essential type */ |