Table of Contents

C type punning

C type punning is reinterpreting a value as a different type via pointers or unions. Converting a float to its bit representation or accessing struct fields as raw bytes uses type punning. Undefined behavior if types have incompatible alignment.

Use type punning cautiously for low-level operations; prefer explicit casts or bit manipulation.

Example

// compile: gcc -o punning punning.c
// run: ./punning
// description: type punning via pointers and unions
 
#include <stdio.h>
#include <stdint.h>
#include <string.h>
 
// Float to bits via union (safe)
typedef union {
    float f;
    uint32_t bits;
} FloatBits;
 
// Pointer type punning (use with care)
int main() {
    // Safe: union
    FloatBits fb;
    fb.f = 3.14159f;
    printf("3.14159 as bits: 0x%08X\n", fb.bits);
 
    // Pointer punning (less safe)
    float f = 2.71828f;
    uint32_t *bits = (uint32_t *)&f;
    printf("2.71828 as bits: 0x%08X\n", *bits);
 
    // Struct member access as bytes
    typedef struct {
        uint16_t x;
        uint16_t y;
    } Point;
 
    Point p = {0x1234, 0x5678};
    uint8_t *bytes = (uint8_t *)&p;
    printf("Point bytes: %02X %02X %02X %02X\n",
           bytes[0], bytes[1], bytes[2], bytes[3]);
 
    return 0;
}

Common patterns

Union approach (safest):

Pointer casting:

Byte-level access:

Undefined behavior risks:

When to use:

Safer alternatives: