https://gcc.gnu.org/bugzilla/show_bug.cgi?id=118141

--- Comment #11 from Andrew Pinski <pinskia at gcc dot gnu.org> ---
(In reply to Richard Yao from comment #10)
> I had thought the strict aliasing rule only applied within function scope,
> although that appears to be a misunderstanding upon checking this:
> 
> https://gist.github.com/shafik/848ae25ee209f698763cffee272a58f8
> 
> This code compiles correctly:
> 
> https://godbolt.org/z/3Tdnac8TE
> 
> For my own education, is this a strict aliasing rule violation too or am I
> okay because I used a union type before the void pointer?

Techincally the above is undefined behavior because one field of an union is
active at a time and you can only access via that one but GCC has an documented
extension about this being well defined.

See
https://gcc.gnu.org/onlinedocs/gcc-14.2.0/gcc/Optimize-Options.html#index-fstrict-aliasing

The practice of reading from a different union member than the one most
recently written to (called “type-punning”) is common. Even with
-fstrict-aliasing, type-punning is allowed, provided the memory is accessed
through the union type. So, the code above works as expected.

Reply via email to