Does a pointer to std::byte have the same aliasing relaxations as char*?

From the current Standard draft ([basic.types.general]/2): For any object (other than a potentially-overlapping subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes ([intro.memory]) making up the object can be copied into an array of char, unsigned char, or std​::​byte ([cstddef.syn]). If the content … Read more

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

Forget casts. Use memcpy. float xhalf = 0.5f*x; uint32_t i; assert(sizeof(x) == sizeof(i)); std::memcpy(&i, &x, sizeof(i)); i = 0x5f375a86 – (i>>1); std::memcpy(&x, &i, sizeof(i)); x = x*(1.5f – xhalf*x*x); return x; The original code tries to initialize the int32_t by first accessing the float object through an int32_t pointer, which is where the rules are … Read more

In C++, is it valid to treat scalar members of a struct as if they comprised an array?

is this code legal? No, it has undefined behavior. The expression &x is a float* that points to a float object and not to the first element of a float array. So, in case idx is 1 or 2 or some other value, the expression (&x)[idx] is (&x)[1] or (&x)[2] respectively which means you’re trying … Read more

Dereferencing type-punned pointer will break strict-aliasing rules

The problem occurs because you access a char-array through a double*: char data[8]; … return *(double*)data; But gcc assumes that your program will never access variables though pointers of different type. This assumption is called strict-aliasing and allows the compiler to make some optimizations: If the compiler knows that your *(double*) can in no way … Read more

Fix for dereferencing type-punned pointer will break strict-aliasing

First off, let’s examine why you get the aliasing violation warnings. Aliasing rules simply say that you can only access an object through its own type, its signed / unsigned variant type, or through a character type (char, signed char, unsigned char). C says violating aliasing rules invokes undefined behavior (so don’t!). In this line … Read more