MISRA Discussion Forums

Full Version: Unions and BitFields
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Regarding usage of bitfields and enum, it is mention thta in certain cases it can be acceptable.

Rule 9-5-1 :  Could you please explain what it means by "all relevant implementation-defined behavious is documented"
Rule 9-6-1 :   Could you please see if the following code example would be compliant.


For exemple would the following code be acceptable with a deviation justification:

   typedef unsigned int  ubitfield_t;

    union EventSource
      {
        EventSource() { Reset(); }
        void    Reset() { all[0] = 0; }

        uint32_t all[1];
        struct EventSourceBits
        {
            ubitfield_t unused                            : 28;

            ubitfield_t unknownId            : 1;
            ubitfield_t InvalidHeader         : 1;
            ubitfield_t wrongCRC              : 1;
            ubitfield_t incompatible          : 1;

        } bits;
      };



Regards,
Charles
Type punning with unions is only sanctioned by the C++ standard in very special cases and not in the code you are showing.

If the union is only needed for Reset all bits to zero, this can be easily achieved by just using

Reset(){
bits = EventSourceBits{};
}
The code uses a union, so it's never going to be compliant with 9-5-1, but may be acceptable with a deviation.

The type-punning in your example is undefined behaviour.

Additionally, packing of the bitfields is going to be heavily dependant on the implementation, e.g. : packing,
alignment, endian-ness, size etc. However, your compiler vendor may define all these properties, but that needs to be verified
and documented in the deviation.