This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Aliasing: reliable code or not?
- From: Ian Lance Taylor <iant at google dot com>
- To: Andrew Pinski <pinskia at physics dot uc dot edu>
- Cc: acahalan at gmail dot com (Albert Cahalan), gcc at gcc dot gnu dot org
- Date: 28 Nov 2006 23:36:19 -0800
- Subject: Re: Aliasing: reliable code or not?
- References: <200611290327.kAT3RhMn016309@localhost.localdomain>
Andrew Pinski <pinskia@physics.uc.edu> writes:
> Here is how I would write it so you can get the best results:
>
> char *foo(char *buf)
> {
> short temp;
> int temp1;
> *buf++=42;
> temp = 0xfeed;
> memcpy(buf, &temp, sizeof(temp));
> buf+=sizeof(temp);
> temp1 = 0x12345678;
> memcpy(buf, &temp1, sizeof(temp1));
> buf+=sizeof(temp1);
> temp1 = 0x12345678;
> memcpy(buf, &temp1, sizeof(temp1));
> buf+=sizeof(temp1);
> return buf;
> }
Or you can use constructor expressions to make this slightly more
elegant, though I retain the assumptions about type sizes:
char *foo1(char* buf){
memcpy(buf, (char[]) { 42 }, 1);
buf += 1;
memcpy(buf, (short[]) { 0xfeed }, 2);
buf += 2;
memcpy(buf, (int[]) { 0x12345678 }, 4);
buf += 4;
memcpy(buf, (int[]) { 0x12345678 }, 4);
buf += 4;
return buf;
}
Ian