Warning: Dereferencing type-punned pointer will break...

I'm making a large project involving Box2D, and right now i'm going through and dealing with the warnings it's been giving me.
It's not a big deal, but I would like to understand.

Warning: dereferencing type-punned pointer will break strict-aliasing rules.

In "b2Math.h"

Code: Select all

inline bool b2IsValid(float32 x)
{
   int32 ix = *reinterpret_cast<int32*>(&x);//this line
   return (ix & 0x7f800000) != 0x7f800000;
}

I looked this warning up, but I didn't quite understand what is going on. I also saw it in another post, but also didn't understand :/
Can someone tell me why the error is occuring and what it's about. Also can I fix it.
In my experience this can be safely ignored. A less strict check for a valid float is to just check that it's non NaN, which you can do by x == x because NaN is not equal to itself. Most of the time, when floats get wacky they end up as NaN.
I came across this too and solved it by changing the header as follows:

Code: Select all

// int32 ix = *reinterpret_cast<int32 *>(&x);
int32 ix;
memcpy(&ix, &x, sizeof(x));


Just wondering if anyone sees any problems with this? It seems equivalent to me, and lets me leave full warnings on in my build, which I like, but I'd rather not introduce some subtle breakage to box2d because I can't stand warnings 😉
What good phrase

Original thread: https://box2d.org/forum/viewtopic.php?t=9631