All Questions

621
votes
9answers
147971 views

What is the strict aliasing rule?

When asking about common undefined behavior in C, souls more enlightened than I referred to the strict aliasing rule. What are they talking about?
53
votes
4answers
6570 views

Is type-punning through a union unspecified in C99, and has it become specified in C11?

A number of answers for the Stack Overflow question Getting the IEEE Single-precision bits for a float suggest using a union structure for type punning (e.g.: turning the bits of a float into a uint32...
178
votes
14answers
66466 views

Purpose of Unions in C and C++

I have used unions earlier comfortably; today I was alarmed when I read this post and came to know that this code union ARGB { uint32_t colour; struct componentsTag { uint8_t b;...
26
votes
5answers
4939 views

Unions and type-punning

I've been searching for a while, but can't find a clear answer. Lots of people say that using unions to type-pun is undefined and bad practice. Why is this? I can't see any reason why it would do any...
23
votes
3answers
2560 views

Aliasing T* with char* is allowed. Is it also allowed the other way around?

Note: This question has been renamed and reduced to make it more focused and readable. Most of the comments refer to the old text. -- According to the standard, objects of different type may not sha...
19
votes
2answers
789 views

union 'punning' structs w/ "common initial sequence": Why does C (99+), but not C++, stipulate a 'visible declaration of the union type'?

Background Discussions on the mostly un-or-implementation-defined nature of type-punning via a union typically quote the following bits, here via @ecatmur ( https://stackoverflow.com/a/31557852/27570...
18
votes
6answers
4765 views

What's a proper way of type-punning a float to an int and vice-versa?

The code below performs a fast inverse square root operation by some bit hacks. The algorithm was probably developed by Silicon Graphics in early 1990's and it's appeared in Quake 3 too. more info Ho...
14
votes
5answers
2385 views

Portable data reinterpretation

I want to reinterpret data of one type as another type in a portable way (C99). I am not talking about casting, I want a reinterpretation of some given data. Also, by portable I mean that it does not ...
20
votes
4answers
2080 views

float bits and strict aliasing

I am trying to extract the bits from a float without invoking undefined behavior. Here is my first attempt: unsigned foo(float x) { unsigned* u = (unsigned*)&x; return *u; } As I unders...
4
votes
4answers
2567 views

union for uint32_t and uint8_t[4] undefined behavior?

In the comments of this answer it is said that it would be undefined behavior to split up an integer into their bytes using a union like follows. The code given at that place is similar though not ide...

Previous Next