Skip to content

Commit 03acbaa

Browse files
committed
Reinterpret cast breaks strict aliasing rules use memcpy
1 parent 9a6237d commit 03acbaa

File tree

1 file changed

+8
-3
lines changed
  • include/boost/math/special_functions

1 file changed

+8
-3
lines changed

include/boost/math/special_functions/next.hpp

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,11 @@
1616
#include <boost/math/special_functions/sign.hpp>
1717
#include <boost/math/special_functions/trunc.hpp>
1818
#include <boost/math/tools/traits.hpp>
19+
#include <boost/math/tools/config.hpp>
1920
#include <type_traits>
2021
#include <cfloat>
2122
#include <cstdint>
23+
#include <cstring>
2224

2325

2426
#if !defined(_CRAYC) && !defined(__CUDACC__) && (!defined(__GNUC__) || (__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ > 3)))
@@ -719,10 +721,11 @@ typename tools::promote_args<T, U>::type float_distance(const T& a, const U& b)
719721
}
720722

721723
// https://randomascii.wordpress.com/2012/01/23/stupid-float-tricks-2/
724+
// https://blog.regehr.org/archives/959
722725
inline std::int32_t float_distance(float a, float b)
723726
{
724727
using std::abs;
725-
constexpr float tol = 2 * (std::numeric_limits<float>::min)();
728+
constexpr auto tol = 2 * (std::numeric_limits<float>::min)();
726729

727730
// 0, very small, and large magnitude distances all need special handling
728731
if (abs(a) == 0 || abs(b) == 0)
@@ -736,8 +739,10 @@ inline std::int32_t float_distance(float a, float b)
736739

737740
static_assert(sizeof(float) == sizeof(std::int32_t), "float is incorrect size.");
738741

739-
const auto ai = *reinterpret_cast<std::int32_t*>(&a);
740-
const auto bi = *reinterpret_cast<std::int32_t*>(&b);
742+
std::int32_t ai;
743+
std::int32_t bi;
744+
std::memcpy(&ai, &a, sizeof(float));
745+
std::memcpy(&bi, &b, sizeof(float));
741746
auto result = bi - ai;
742747

743748
if (ai < 0 || bi < 0)

0 commit comments

Comments
 (0)