Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
operations on bit fields?
#1
Hi.

I wonder whether there's any MISRA rule that forbids operations on bit fields?
The question came up as I received some code from another project which contains a bit field, several defines (e.g. #define ENABLE_XY 0x80) and (logical) operations on it (e.g. "if (bitfield | ENABLE_XY)").

However, my compiler implements inverse arrangement for bit fields and has no switch to change it, so the old code now produces wrong results.
But the old code has passed the MISRA check. Therefore my question is: Is that code just an example of "worst coding style" or should there be a MISRA rule which prevents the programmer from such carelessness?

Best regards,

mic
<t></t>
Reply
#2
Rule 3.5 covers this.
I would also argue that this also violates Rule 18.2.
<t></t>
Reply
#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


Forum Jump:


Users browsing this thread: 2 Guest(s)