Steve Albright - 2021-09-09

constParameter - Parameter 'data' can be declared with const

https://en.cppreference.com/w/cpp/language/union

namespace constParameterFalsePositiveWithUnion
{
   union UnionToSetStructData
   {
      struct
      {
         unsigned long one:8;
         unsigned long two:13;
         unsigned long three:11;
         unsigned long four:3;
         unsigned long five:5;
      } FourByteStruct;
      unsigned char TheFilledData[4]; // intentionally same size as the struct in bytes
   };

   bool GetData(UnionToSetStructData& data) // data is an in/out parameter
   {
      UnionToSetStructData aUnion;

      // comment out all the sets to 0 and you get unusedStructMember warnings for each but
      // per the rules of unions that doesn't make sense because TheFilledData is last active
      // This looks like https://trac.cppcheck.net/ticket/10293 but I am using 2.5 so it doesn't seem like it is fixed yet
      aUnion.FourByteStruct.one = 0;
      aUnion.FourByteStruct.two = 0;
      aUnion.FourByteStruct.three = 0;
      aUnion.FourByteStruct.four = 0;
      aUnion.FourByteStruct.five = 0;

      memcpy(aUnion.TheFilledData, data.TheFilledData, sizeof(data)); // just so aUnion.TheData is considered active in the union
      memcpy(data.TheFilledData, aUnion.TheFilledData, sizeof(data)); // example code, we wouldn't restore this normally
      return true;
   }
}