Document: WG14 N1463

Type punning example

Submitter: Fred J. Tydeman (USA)
Submission Date: 2010-05-10
Related documents: N1431
Subject: Type punning example

Problem: "type punning" is mentioned in a footnote. It seems to me that the idea needs to be fleshed out with an example.


Add the following example to Structure and union members

EXAMPLE nn: A non-static complex object may be created from two real values via type punning:

#include  <math.h>
  union fc2 {           /*, paragraph 3, type punning */
    float f[2];         /* 6.2.5, paragraph 13, layout of complex */
    float _Complex fc;
  float _Complex fc0 = (union fc2){INFINITY, NAN}.fc;
  float _Complex fc1 = (union fc2){.f[0] = -0.f, .f[1] = 1.f}.fc;

defines and initializes fc0 with the value /math infinity symbol/ + iNAN, fc1 with the value -0.f + i, Note: This usage does not allow for static initialization.

Add to the rationale in the section on unions:

Unions may be used to do type punning. That is, to reinterpret an object representation as a new type. This is different than a conversion to a new type.