MISRA.CAST.CONSTMISRA C 2012 Rule 11.8: A cast shall not remove any const or volatile qualification from the type pointed to by a pointerCast operation removes const or volatile modifier from a pointer or reference. C90 [Undefined 12, 39, 40], C99 [Undefined 30, 61, 62] Category: Required Analysis: Decidable, Single Translation Unit Applies to: C90, C99 RationaleAny attempt to remove the qualification associated with the addressed type by using casting is a violation of the principle of type qualification. Note: The qualification referred to here is not the same as any qualification that may be applied to the pointer itself.
Some of the problems that might arise if a qualifier is removed from the addressed object are:
Note: Removal of the C99 restrict type qualifier is benign.
Exampleuint16_t x; uint16_t * const cpi = &x; /* const pointer */ uint16_t * const *pcpi; /* pointer to const pointer */ uint16_t * *ppi; const uint16_t *pci; /* pointer to const */ volatile uint16_t *pvi; /* pointer to volatile */ uint16_t *pi; pi = cpi; /* Compliant - no conversion no cast required */ pi = (uint16_t *)pci; /* Non-compliant */ pi = (uint16_t *)pvi; /* Non-compliant */ ppi = (uint16_t * *)pcpi; /* Non-compliant */ MISRA-C 2004 Rule 11.5 (required): A cast shall not be performed that removes any const or volatile qualification from the type addressed by a pointer.Cast operation removes const or volatile modifier from a pointer or reference. [Undefined 39, 40] Any attempt to remove the qualification associated with the addressed type by using casting is a violation of the principle of type qualification. Notice that the qualification referred to here is not the same as any qualification that may be applied to the pointer itself. Exampleuint16_t x; uint16_t * const cpi = &x; /* const pointer */ uint16_t * const * pcpi; /* pointer to const pointer */ const uint16_t * * ppci; /* pointer to pointer to const */ uint16_t * * ppi; const uint16_t * pci; /* pointer to const */ volatile uint16_t * pvi; /* pointer to volatile */ uint16_t * pi; ... pi = cpi; /* Compliant - no conversion no cast required */ pi = (uint16_t *)pci; /* Not compliant */ pi = (uint16_t *)pvi; /* Not compliant */ ppi = (uint16_t * *)pcpi; /* Not compliant */ ppi = (uint16_t * *)ppci; /* Not compliant */ MISRA C++ 2008 Rule 5-2-5 (required): A cast shall not remove any const or volatile qualification from the type of a pointer or reference.[Undefined 7.1.5.1(4, 7)] RationaleRemoval of the const or volatile qualification may not meet developer expectations as it may lead to undefined behaviour. Examplevoid f ( const char_t * p ) { *const_cast< char_t * >( p ) = '\0'; // Non-compliant } int main ( ) { f ( "Hello World!" ); } |