This code demonstrates type punning, where the bitwise representation of...

September 2, 2025 at 12:24 PM

int main(){ float y = .123f; long i = *(long *) &y; y = *(float*) &i; }

This code demonstrates type punning, where the bitwise representation of a float is interpreted as a long integer, then converted back to a float.

Here’s how the code works step by step:

  1. float y = .123f;

    • A float variable y is initialized with the value 0.123.
  2. long i = *(long *) &y;

    • Here, the address of the float variable y is cast to a pointer of type long *, and the value at that address is dereferenced and stored in the long variable i.
    • This operation reinterprets the raw binary representation of y (as a float) as a long. It does not perform any conversion of the numerical value, but simply treats the binary bits as if they were a long.
  3. y = *(float *) &i;

    • The address of the long variable i is cast back to a pointer of type float *, and the value at that address is dereferenced and assigned back to the float variable y.
    • This operation reinterprets the binary representation of i (as a long) as a float. Again, no numerical conversion happens here; the code simply reinterprets the bits.

Key Points:

  • This is an example of type punning, which is generally undefined behavior in C and C++ due to strict aliasing rules, as the compiler assumes that objects of different types do not share memory. In practice, however, many compilers allow this behavior on common architectures.
  • The binary representation of 0.123 as a float is preserved as it is cast between the float and long types. At the end, y will have the same original value (0.123) if no corruption or unexpected behavior occurs due to the type punning.

Practical Use:

This type of code is often used in low-level programming for tasks like inspecting or manipulating the raw bitwise representation of a floating-point number, though more portable and safer approaches (e.g., using memcpy) are preferred.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node