I recently came across a third party code snippet inside our application that does not make any sense to me. What puzzled me first it that it has been in production for at least 10 years and seemed to work. It is basically a union of bit fields:
union
{
unsigned longitude : 2; //!< status of the longitude (offset: 0)
unsigned latitude : 2; //!< status of the latitude (offset: 2)
unsigned xPosition : 2; //!< status of the x position relative to starting position (offset: 4)
unsigned yPosition : 2; //!< status of the y position relative to starting position (offset: 6)
// ... Many more 2-bit fields... Total 26 fields
unsigned reserved : 12;
unsigned long status[2]; //!< raw status data
} status;
I am pretty sure that this is a bug and what the author really wanted to write was:
union
{
struct
{
unsigned longitude : 2; //!< status of the longitude (offset: 0)
unsigned latitude : 2; //!< status of the latitude (offset: 2)
unsigned xPosition : 2; //!< status of the x position relative to starting position (offset: 4)
unsigned yPosition : 2; //!< status of the y position relative to starting position (offset: 6)
// ... Many more 2-bit fields... Total 26 fields
unsigned reserved : 12;
};
unsigned status[2]; //!< raw status data (should not be long!)
} status;
The reason it was kind of working is that only one of those 26 bit fields was actually used! But this bug made raised a few questions:
- Is the compiler required to use the same first 2 bits of the same
unsignedfor all fields (despite what the comments say)? - Is there any real usage for a
unionof bit fields? I cannot think of any situation where this would make sense. - If that doesn't make any sense, how come that no compilers we are using (neither Clang, GCC nor MSVC) were issuing any warning?