![]() |
|
MISRA-C:2004 Rule 10.5: (Required) |
|
||||
![]() | |||||||
uint8_t port=0x5aU; uint8_t result_8; uint16_t result_16; uint16_t mode; result_8=(~port)>>4;/* not compliant */
~port is 0xffa5 on a 16-bit machine but 0xffffffa5 on a 32-bit machine. In either case the value of result is 0xfa, but 0x0a may have been expected. This danger is avoided by inclusion of the cast as shown below:
result_8=((uint8_t)(~port))>>4;/* compliant */result_16=((uint16_t)(~(uint16_t)port))>>4;/* compliant */
A similar problem exists when the << operator is used on small integer types and high order bits are retained. For example:
result_16=((port<<4)&mode)>>6;/* not compliant */
The value in result_16 will depend on the implemented size of an int. Addition of a cast avoids any ambiguity.
result_16=((uint16_t)((uint16_t)port<<4)&mode)>>6;/* compliant */
No cast is required if the result of the bitwise operation is:
QAC messages that encompass this guideline:
| 4397 | An expression which is the result of a ~ or << operation has not been cast to its essential type. |
| 4398 | An expression which is the result of a ~ or << operation has been cast to a different essential type category. |
| 4399 | An expression which is the result of a ~ or << operation has been cast to a wider type. |
| 4498 | An expression which is the result of a ~ or << operation has been converted to a different essential type category on assignment. |
| 4499 | An expression which is the result of a ~ or << operation has been converted to a wider essential type on assignment. |
|
||
(c) The Motor Industry Research Association, 2004
|
QA C Source Code Analyser 8.1.2
MISRA-C:2004 Compliance Module 3.2 © 2013 Programming Research www.programmingresearch.com |
Personality Groups | Glossary | Message Index | MISRA-C:2004 Rule Index | Contents |