V1014. Structures with members of real type are compared byte-wise.
The analyzer has detected a suspicious comparison of two structures containing members of type float or double.
Consider the following example:
struct Object
{
int Length;
int Width;
int Height;
float Volume;
};
bool operator == (const Object &p1, const Object &p2)
{
return memcmp(&p1, &p2, sizeof(Object)) == 0;
}
Since the 'Object' structure contains floating-point numbers, comparing them using the 'memcmp' function could have an unexpected result. For example, the numbers -0.0 and 0.0 are equivalent but have different bit representation. Two NaN's have the same representation, but they are not equivalent. It may make sense to use the == operator or compare those variables to a certain precision.
Suppose we want to compare class members using the == operator. In this case, we could delete the 'operator ==' part entirely as the compiler can handle it on its own by implementing the comparison operator by default. However, suppose we do need to implement it as our custom function to compare the 'Volume' members to a certain precision. The fixed version would then look like this:
bool operator == (const Object &p1, const Object &p2)
{
return p1.Length == p2.Length
&& p1.Width == p2.Width
&& p1.Height == p2.Height
&& fabs(p1.Volume - p2.Volume) <= FLT_EPSILON;
}
This diagnostic is classified as:
|