Barr Group TwitterBarr Group Vimeo

Rules:

5.3.a. Bit-fields shall not be defined within signed integer types.

5.3.b. None of the bitwise operators (i.e., &, |, ~, ^, <<, and >>) shall be used to manipulate signed integer data.

5.3.c. Signed integers shall not be combined with unsigned integers in comparisons or expressions. In support of this, decimal constants meant to be unsigned should be declared with a ‘u’ at the end.

Example:

uint16_t  unsigned_a = 6u;
int16_t	  signed_b   = -9;

if (unsigned_a + signed_b < 4)
{
    // Execution of this block appears reliably logical, as -9 + 6 is -3
    ...
}
// ... but compilers with 16-bit int may legally perform (0xFFFF – 9) + 6.

Reasoning: Several details of the manipulation of binary data within signed integer containers are implementation-defined behaviors of the ISO C standards. Additionally, the results of mixing signed and unsigned integers can lead to data-dependent outcomes like the one in the code above.7 Beware that the use of C99’s fixed-width integer types does not by itself prevent such defects.

Enforcement: Static analysis tools can be used to detect violations of these rules.


Footnotes

[7] [MISRA-C] describes problems that can arise from mixing C’s “essential types” at length in its Appendix C and Appendix D.

Comments:

When I tried it, the example code on this page took the expected path.

Works on one compiler is not the same as works on all compilers...

What’s happening and how it’s done. Get in the know.

Sign Up for Our Newsletter

Receive free how-to articles, industry news, and the latest info on Barr Group webinars and training courses via email. 

To prevent automated spam submissions leave this field empty.