by LegionMammal978 · 1y ago · 0 comments
Apart from memcpy(), the 'allowed' methods include unions in C (writing to one member and reading from another), and bit_cast<T>() and std::start_lifetime_as<T>() in C++.
The first is to allocate the memory using char a[sizeof(float)]. In C, char pointers may alias anything, so then you can do pointer conversions that would normally be undefined behavior and it should work. The other option is to use the non-standard __attribute__((__may_alias__)) on the pointer.
By the way, using union types for this is technically undefined behavior in the C and C++ standards, but GCC and Clang decided to make it defined as an implementation choice. Other compilers might not.
And note that while char can alias anything, the reverse is not true: i.e. you can't generally cast a char array to anything else and expect sensible behaviour. There are ways to make this work (placement new in C++ for example), but it is not a way to escape TBAA: if you store a float in char array you can't then cast it to int with impunity.
https://open-std.org/jtc1/sc22/wg14/www/docs/dr_283.htm
It is not part of C99. It also is not part of the C standard since no subsequent C standard adopted it according to the GCC developers:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=118141#c13
A read of the C11 standard draft, which would have this amendment if it were accepted by the C standards committee, shows that this has not been added:
https://open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
Type punning via union types is therefore undefined behavior unless your compiler implements an extension to define it like GCC and Clang do.
I'm probably an optimist.
(I am not a C or C++ expert.)