Type punning

In computer science, a type punning is any programming technique that subverts or circumvents the type system of a programming language in order to achieve an effect that would be difficult or impossible to achieve within the bounds of the formal language.

The function to bind an opened but uninitialized socket to an IP address is declared as follows: The bind function is usually called as follows: The Berkeley sockets library fundamentally relies on the fact that in C, a pointer to struct sockaddr_in is freely convertible to a pointer to struct sockaddr; and, in addition, that the two structure types share the same memory layout.

In other words, the sockets library uses type punning to implement a rudimentary form of polymorphism or inheritance.

In these cases, documenting all such assumptions in comments, and introducing static assertions to verify portability expectations, helps to keep the code maintainable.

Practical examples of floating-point punning include fast inverse square root popularized by Quake III, fast FP comparison as integers,[1] and finding neighboring values by incrementing as an integer (implementing nextafter).

Even when data size and pointer representation match, however, compilers can rely on the non-aliasing constraints to perform optimizations that would be unsafe in the presence of disallowed aliasing.

A naive attempt at type-punning can be achieved by using pointers: (The following running example assumes IEEE-754 bit-representation for type float.)

The C standard's aliasing rules state that an object shall have its stored value accessed only by an lvalue expression of a compatible type.

Although on GCC and LLVM this particular program compiles and runs as expected, more complicated examples may interact with assumptions made by strict aliasing and lead to unwanted behavior.

These examples could be used to create strange conversions, although, in some cases, there may be legitimate uses for these types of constructs, such as for determining locations of particular pieces of data.

Assigning a value to an integer variant of a pointer would allow examining or writing to any location in system memory: This construct may cause a program check or protection violation if address 0 is protected against reading on the machine the program is running upon or the operating system it is running under.