c-type-punning
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):
- Define union of both types
- Access via appropriate member
- No pointer casting, compiler-approved
Pointer casting:
- Cast pointer to different type
- Dereference to get value
- Risk: undefined behavior if misaligned
Byte-level access:
(uint8_t *)to inspect structure bytes- Common for networking, serialization
- Endianness-dependent
Undefined behavior risks:
- Misaligned access (CPU fault)
- Type punning incompatible types
- Strict aliasing rules violation
When to use:
- Float↔bits conversion
- Serialization/deserialization
- Hardware register access
- Network protocol parsing
Safer alternatives:
- memcpy for type conversion
- Explicit bit manipulation
- Bit fields for structured access
c-type-punning.md · Last modified: by 127.0.0.1
