operations on bit fields? - Printable Version +- MISRA Discussion Forums (https://forum.misra.org.uk) +-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4) +--- Forum: General Questions (https://forum.misra.org.uk/forumdisplay.php?fid=27) +--- Thread: operations on bit fields? (/showthread.php?tid=858) |
operations on bit fields? - mic - 31-10-2011 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 Re: operations on bit fields? - William Forbes - 03-11-2011 Rule 3.5 covers this. I would also argue that this also violates Rule 18.2. Re: operations on bit fields? - misra-c - 07-11-2011 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) 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. |