Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
is a cast compliant with Rule 12.4
#1
Is the cast in the following code compliant with MISRA2023 Rule 12.4, assuming a machine having int as 32 bit?


Code:
#include <stdint.h>

#define USEFUL_BIT ((uint16_t)0x0020u)

uint16_t clear_useful_bit(uint16_t bitmask)
{
  uint16_t cleared_mask = bitmask;

  cleared_mask &= (uint16_t)~USEFUL_BIT;

  return cleared_mask;
}

According to Appendix D.7.5 1.1 the result of ~ is the UTRL of the result. Assuming an 32 bit integer machine this would be 4294967263u. The result of the cast to uint16_t would be perform a "repeatedly [...] subtracting one more than the maximum value that can be represented in the new type until the value is in the new type" which leads to 65503.

Is this type conversion treated as "unsigned integer wrap-around" in the sense of Rule 12.4 ?
Reply
#2
The conversion is defined in terms of mathematical addition or subtraction operations on the value of the expression, but these do not imply that C addition or subtraction operations actually occur, as clarified by footnote 60 (C11) and footnote 51 (C24), whereas this Rule is understood only to apply to operations resulting from the C expression language.

In this example, the ~ operator results in extension, which is not a wraparound.

Therefore this Rule does not apply.
Posted by and on behalf of the MISRA C Working Group
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)