ETLCPP / etl

Embedded Template Library
https://www.etlcpp.com
MIT License
2.17k stars 388 forks source link

Compilation warning / error for hash.h with -Wfloat-equal flag #793

Closed vasiliisredasolutions closed 10 months ago

vasiliisredasolutions commented 10 months ago

Environment:

/usr/bin/c++ --version
c++ (Ubuntu 10.5.0-1ubuntu1~20.04) 10.5.0
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

When trying to compile with -Wfloat-equal the following errors occured for hash.h:

include/etl/hash.h: In member function ‘size_t etl::hash<float>::operator()(float) const’:
include/etl/hash.h:401:15: error: comparing floating-point with ‘==’ or ‘!=’ is unsafe [-Werror=float-equal]
        if (v == -0.0f)

for the code:

if (v == -0.0f)
{ // -0.0 and 0.0 are represented differently at bit level
  v = 0.0f;
}

The same behavior is at lines 402, 436 and 470 of hash.h.

Proposed solution is (checked on the same environment with -std=c++11):

union
{
  size_t s;
  float  v;
} u;
u.v = -0.0f;

if (*reinterpret_cast<size_t*>(&v) == u.s)
{ // -0.0 and 0.0 are represented differently at bit level
  v = 0.0f;
}
u.v = v;

return u.s;
vasiliisredasolutions commented 10 months ago

Verions of ETL affected 20.37.0 and above.

jwellbelove commented 10 months ago

This is a duplicate of #779