Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unions and BitFields
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:

[font=Consolas, "Courier New", monospace]   typedef unsigned int  ubitfield_t;[/font]

    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;

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

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.
Posted by and on behalf of
the MISRA C++ Working Group

Forum Jump:

Users browsing this thread: 1 Guest(s)