Comment

Comment by ufo

Suppose you want to look at the bits of a floating point number, as though it were an integer. The type punning way to do that would be to access a double in memory through an integer pointer:

    double d = 3.14;
    int64_t *p = (int64_t *) &d; // !!!
    int64_t n = *p;
The union aliasing way would be to makeset the double field in a union and read the integer field back:

    typedef union {
        double d;
        int64_t n;
    } int_or_double;

    int_or_double u;
    u.d = 3.14
    int64_t n = u.n
According to the standard, the union aliasing approach is allowed, but the type punning one is undefined behavior.

---------

The standard team decided to forbid type punning to allow compilers to implement more optimizations. They still allow union aliasing because they felt there should still be a way to do low-level type casts if for those that absolutely want to.

parent ufo 8 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton