ArticleslgStudy

science

Type punning

Type punning is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Type punning rather than just read about it. In short: In computer science, 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. In C and C++, constructs such as pointer type conversion and union — C++ adds reference type conversion and reinterpret_cast to this list — are provided in order to…

Key takeaways

  • Type punning belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Type punning to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Type punning from memory before moving on to harder problems.

Reference excerpt

In computer science, 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. In C and C++, constructs such as pointer type conversion and union — C++ adds reference type conversion and reinterpret_cast to this list — are provided in order to permit many kinds of type punning, although some kinds are not actually supported by the standard language. In the Pascal programming language, the use of records with variants may be used to treat a particular data type in more than one manner, or in a manner not normally permitted.

Sockets example One classic example of type punning is found in the Berkeley sockets interface. 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. Therefore, a reference to the structure field my_addr->sin_family (where my_addr is of type struct sockaddr*) will actually refer to the field sa.sin_family (where sa is of type struct sockaddr_in). In other words, the sockets library uses type punning to implement a rudimentary form of polymorphism or inheritance. Often seen in the programming world is the use of "padded" data structures to allow for the storage of different kinds of values in what is effectively the same storage space. This is often seen when two structures are used in mutual exclusivity for optimization.

Floating-point example Not all examples of type punning involve structures, as the previous example did. Suppose we want to determine whether a floating-point number is negative. We could write:

However, supposing that floating-point comparisons are expensive, and also supposing that float is represented according to the IEEE floating-point standard, and integers are 32 bits wide, we could engage in type punning to extract the sign bit of the floating-point number using only integer operations:

Note that the behaviour will not be exactly the same: in the special case of x being negative zero, the first implementation yields false while the second yields true. Also, the first implementation will return false for any NaN value, but the latter might return true for NaN values with the sign bit set. Lastly we have the problem wherein the storage of the floating point data may be in big endian or little endian memory order and thus the sign bit could be in the least significant byte or the most significant byte. Therefore the use of type punning with floating point data is a questionable method with unpredictable results. This kind of type punning is more dangerous than most. Whereas the sockets example relied only on guarantees made by the C programming language about structure layout and pointer convertibility, the float example relies on assumptions about a particular system's hardware. The C99 Language Specification ( ISO9899:1999 ) has the following warning in section 6.3.2.3 Pointers : "A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined." Therefore one should be very careful with the use of type punning. Some situations, such as time-critical code that the compiler otherwise fails to optimize, may require dangerous code. 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, and finding neighboring values by incrementing as an integer (implementing nextafter).

By language

C and C++ In addition to the assumption about bit-representation of floating-point numbers, the above floating-point type-punning example also violates the C language's constraints on how objects are accessed: the declared type of x is float but it is read through an expression of type unsigned int. On many common platforms, this use of pointer punning can create problems if different pointers are aligned in machine-specific ways. Furthermore, pointers of different sizes can alias accesses to the same memory, causing problems that are unchecked by the compiler. 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.

Use of pointers 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. The types float and int32_t are not compatible, therefore this code's behavior is undefined. 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. The option -fno-strict-aliasing will ensure correct behavior of code using this form of type-punning, although using other forms of type punning is recommended.

Use of union In C, but not in C++, it is sometimes possible to perform type punning via a union.

Accessing my_union.i after most recently writing to the other member, my_union.f, is an allowed form of type-punning in C, provided that the member read is not larger than the one whose value was set (otherwise the read has unspecified behavior). The same is syntactically valid but has undefined behavior in C++, where only the last-written member of a union is considered to have any value at all. For another example of type punning, see Stride of an array.

Use of memcpy memcpy is a safe and portable method of type punning, blessed in the C++ standard. Clang and GCC include specific optimizations for memcpy calls of this sort.

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Type punning

Start with the simplest possible case. Write down what Type punning claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Type punning before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Type punning ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Type punning

In research
Type punning appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Type punning in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Type punning is common in secondary-school and first-year university syllabi. It links to neighbouring topics Programming constructs, so understanding it makes those chapters shorter.
In everyday life
Look for Type punning outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Type punning” →

How to study Type punning in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Type punning means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Type punning out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Type punning in simple terms?

In computer science, 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. In C and C++, constructs such as pointer typ…

Why does Type punning matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Type punning?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Type punning.

Tags

  • Programming constructs

Keep exploring