Type punning

Type punning

Type punning refers to techniques that allow accessing an object as a different type by taking advantage of the memory layout. This allows bypassing the strict aliasing rules in C++. Here's an explanation of how it works and some common use cases.

How Type Punning Works

Type punning involves leveraging the fact that the memory layout of some types may match, even if they are considered different types by the compiler. Some examples:

  • An int and a float may both occupy 4 bytes.
  • A struct with exactly one int member will match the layout of just an int.

This allows code to reinterpret the binary representation of the same memory as different types.

Some methods of type punning include:

Unions

union Data {
  int i; 
  float f;
};

Data data; 
data.i = 10;

// Now access the same memory as a float
std::cout << data.f;