Boost logo

Boost :

From: Matt Austern (austern_at_[hidden])
Date: 2001-04-20 12:19:56


Gabriel Dos Reis wrote:
>
> Matt Austern <austern_at_[hidden]> writes:
>
> | There might be, depending on what kind of initialization we're
> | talking about. But since this is inherently platform specific
> | anyway, you can always use platform-specific initialization
> | tricks if you have to.
> |
> | And in some cases you might not have to use any such tricks.
> | I'm thinking of something like this:
> |
> | union fp_constant {
> | unsigned int n;
> | float f;
> | };
> |
> | fp_constant internal_pi = { 0x40490fdb };
> | float pi = internal_pi.f;
>
> Matt, doesn't that belong to undefined behaviour-land?

Absolutely! This is not portable code. It's unportable in
several ways:
 (1) As Gaby pointed out, it's undefined behavior to
     store something in one union member and access it
     through another. It works on some platforms, not
     on others.
 (2) It assumes that float and unsigned int are both 32
     bits.
 (3) It makes assumptions about integer endianness, and
     about which bits go where in the floating-point
     representation.

There's no doubt, this is evil stuff. However, it's the
sort of thing you have to do if you want exact control
over the binary expansion of a floating point number. You
can't do it portably. You'll see code like this (or code
that does equally evil things, like calling inline
assembly) in a commercial libm.

                        --Matt


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