MISRA Discussion Forums
Unions and BitFields - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: MISRA C++:2008 rules (https://forum.misra.org.uk/forumdisplay.php?fid=19)
+---- Forum: 6.9 Classes (C++) (https://forum.misra.org.uk/forumdisplay.php?fid=138)
+---- Thread: Unions and BitFields (/showthread.php?tid=1627)



Unions and BitFields - [email protected] - 05-07-2022

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


RE: Unions and BitFields - PeterSommerlad - 08-07-2022

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{};
}


RE: Unions and BitFields - misra cpp - 08-07-2022

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.