Boost logo

Boost :

From: Johan Råde (rade_at_[hidden])
Date: 2006-08-03 11:49:32


Guillaume Melquiond wrote:
>>
>> bool signbit(float x)
>> {
>> const float one = 1;
>> const float neg_one = -1;
>> const int sign_mask = reinterpret_cast<const int&>(one)
>> ^ reinterpret_cast<const int&>(neg_one);
>> return reinterpret_cast<int&>(x) & sign_mask;
>> }
>
> You are invoking undefined behavior here: you are accessing a float
> through a reference to an int. As a consequence, GCC produces code that
> accesses uninitialized memory (since one and neg_one are optimized away)
> and returns random values. You have to use char* pointers and memcopies
> so that there is no aliasing issue.
>
> Best regards,
>
> Guillaume
>
> _______________________________________________
> Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
>

Thanks for the information.

All I need to do is to get my hands on the bit patterns of 1.0f, -1.0f
and x. Do I really have to copy the memory to do that?
That seems like overkill.
Can't I just form pointers to the float constants, cast the pointers to
int pointers, and dereference them?
Something like

>> bool signbit(float x)
>> {
>> const float one = 1;
>> const float neg_one = -1;
>> const int sign_mask = *static_cast<const int*>(&one)
>> ^ *static_cast<const int*>(&neg_one);
>> return *static_cast<int*>(&x) & sign_mask;
>> }

--Johan


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk