Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use C++ union on embedded software

I'm an embedded software (firmware) developer (C++) and sometimes I need to convert data between types, for example

  • an array of 4 bytes, need to be written to the hardware in a single 32bit register
  • a float variable needs to be transmitted in a message as bytes

In order to do the conversion properly, I am using a union, to store the data, so I can read/write it in both ways, for example

union {
    uint8_t asByte[lengthInBytes]{};         // interprete the data as 16 bytes
    uint32_t asUint32[lengthInWords];        // interprete the data as 4 32bit words
} state;

Now I am running static code checking on my code (using SonarCloud) and this is flagging an issue on this construct :

Add a discriminant to this wrapped undiscriminated union or replace it with an "std::variant"

I don't want to use the std:: library containers because I need to avoid using dynamic memory allocation, and often it's also an overkill...

So how can I resolve this 'codeSmell', or should I just ignore/accept it in my use case ?

like image 580
Strooom Avatar asked Sep 01 '25 03:09

Strooom


1 Answers

Thanks for all the useful remarks,

Seems like std::bitcast is the right way to do this.
It requires C++20 but I think I'm ok with that.

like image 186
Strooom Avatar answered Sep 02 '25 15:09

Strooom