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

--- Comment #13 from Andrew Pinski <pinskia at gcc dot gnu.org> ---
(In reply to Richard Yao from comment #12)
> (In reply to Andrew Pinski from comment #11)
> > (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.
> 
> Would I be correct to think you were were responding as if this were C++
> code, rather than responding as if this were C code? I ask because I cannot
> use std::bit_cast in C and I thought type punning via unions was allowed by
> the C standard, while the C++ standard disallowed it.

Type punning via unions is undefined behavior in both c and c++.

Reply via email to