Type Punning
Type punning in C++ refers to the practice of accessing the same memory location as if it were a different data type than the one it was originally declared as. This technique allows you to interpret the binary representation of one data type as if it were another.
Here's a brief explanation of type punning:
Purpose: It's often used for low-level operations, like bit manipulation or when dealing with hardware interfaces.
Implementation: Typically done through pointer casting or unions.
Risks: It can lead to undefined behaviour if not used carefully, especially with strict aliasing rules.
Example: Converting between float and int without using conversion functions.
Here is a simple example:
Try it here.
In this example, you can see we
We stored
a
as double with value of2
.If you look at the memory output, double takes 8 bytes in memory. i.e.
|00| |00| |00| |00| |00| |00| |00| |40|
is double representation of value2
in bytes.Now, we read memory address of
a
and cast it as an integer pointer and store it in variableb
.Variable
b
is read as an integer, hence only 4 bytes will read instead of 8, which will be|00| |00| |00| |00|
, hence will be read as0
.This is what type punning is, we are reading data as a different type.
Note:
printMem()
function itself uses concepts of type punning to read memory as char and print on console.
Next, we will see how we can use this with structures.
Last updated