Store Float16 variables
Is there something particular wrong with the following implementation which could lead to major issues?


Yes; the union seems to be used in a way that is actually Undefined Behavior.  Let’s see…

    f32.IEEE.Sign = bits.IEEE.Sign;
    f32.IEEE.Exp  = bits.IEEE.Exp + 112; 
    f32.IEEE.Man  = bits.IEEE.Man &lt;&lt; 13;

    return f32.Float;


Yes, you are reading from the Float member that is never written to, the optimizer can know that it is not the active member, and act as if the program never reaches this point.  Anything is possible, including crashing.

We have seen the optimizers get more and more aggressive, taking advantage of U.B., breaking “bad” code that worked historically.  So, it is a real concern.  In any case, the layout of the bit fields is up to the implementation; that is only an issue if you plan on saving these 16-bit values to files.

See Scott Schurr’s presentation on this.  Your specific case is handled toward the end, and he shows that of all the work-arounds, using intrinsic memcpy with the items known to be properly aligned will be completely optimized out by the compiler, generating the code you really intended with the union!



See also ⧺ES.9.



float   f32 = (float)f16;


Don’t use C-style casts.  Any appearance of such a cast is a flag for code review; casts that are actually needed should be function style, specialized, or use clearly named helper functions.

You supplied an implicit conversion, so you don’t need this cast at all.