Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
operations on bit fields?
#3
As has already been pointed out, the relevant MISRA C rule is Rule 3.5, "If it is being relied upon, the implementation defined behaviour and packing of bitfields shall be documented." This is not a rule that can be checked automatically, although some tools may be able to identify some possible problems with use of bitfields.

It is not clear how the code fragment:

Code:
if (bitfield | ENABLE_XY)
depends on the order of bits in the bitfield. The bitfield will be promoted to int or unsigned int, depending on its width. The result of the expression "bitfield | ENABLE_XY" does not depend on the order in which the bits occur.

If bitfield is an expression that denotes the storage unit that holds the bits then its value will indeed depend on the order in which the bits are allocated within the storage unit. However, the expression "bitfield | ENABLE_XY" will always evaluate to non-zero so the outcome of the if condition is not affected by the order in which the bits are allocated.

If the expression were "bitfield & ENABLE_XY" then it might be zero for some bit orderings and non-zero for others but again, only if "bitfield" denotes the storage unit containing the bits.

In summary, if you are accessing bitfields using the . or -> operators then the layout of the bitfield does not matter. If you are attempting to access the storage units that contain bitfields, for example by means of unions or pointers, your code is likely to be non-portable. Even worse, a small change to the source code, a change in compiler version or even a change in compiler options might change way in which bitfields are packed.
Posted by and on behalf of the MISRA C Working Group
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 3 Guest(s)