This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Question on strict aliasing in C.


Paul Smith <paul@mad-scientist.net> writes:

> On Mon, 2011-07-04 at 19:17 +0200, Georg-Johann Lay wrote:
>> >> double copysign (double x, double y)
>> >> {
>> >>     unsigned short * const px = (unsigned short*)(char*)&x + 3;
>> >>     unsigned short * const py = (unsigned short*)(char*)&y + 3;
>
> I don't get why you have the (char*) cast here?
>
>> >>     *px = *px & ~MASK | *py & MASK;
>> >>     return x;
>> >> }
>> >>
>> >> So I want to reassure me if the code is ok or not.
>> > 
>> > It's not.  Tey're wrong, you're right.
>
> So let me ask: if you change the last line to:
>
> 	return *px;
>
> instead, is it now OK WRT aliasing rules?

No.

Here is the simple way to think about it: the type you use to store the
value must be the type you use the retrieve the value.

There are various exceptions but none of them apply here.  The most
interesting exception is that you can store a value via a char* pointer
and retrieve it using a different type, and you can store a value via
some random type and retrieve it using a char* type.

Ian


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]