andersch.dev

<2025-04-16 Wed>

Type punning

Type punning in programming allows accessing data of one type as if it were another type by reinterpreting the same memory location.

Type punning can lead to undefined behavior when performed incorrectly, particularly with strict aliasing violations.

Union-based punning (valid in C)

union Punner {
    float f;
    int i;
};

union Punner p;
p.f = 3.14f;
printf("%x\n", p.i); // Access float bits as int

Pointer casting (violates strict aliasing)

float f = 3.14f;
int* ip = (int*)&f; // Dangerous: breaks strict aliasing

memcpy approach (safe, standard-compliant):

float f = 3.14f;
int i;
memcpy(&i, &f, sizeof(float)); // Standards-compliant