Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unions and BitFields
#1
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
Reply
#2
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{};
}
Reply
#3
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.
Posted by and on behalf of
the MISRA C++ Working Group
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)