Re: alias question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 02/18/2011 09:35 AM, xorbe wrote:
#include<stdio.h>
char b[4] = {0,0,0,0};
const short*w((short*)b);
const int*d((  int*)b);
void print() {printf("%02x%02x%02x%02x %04x%04x %08x\n",
                      b[3],b[2],b[1],b[0],w[1],w[0],d[0]);}
int main() {
   print();
   for (int i(0); i<4; ++i) { b[i] = i+1; print(); }
}
You're right. This might make it clearer, it's a version that's valid C and looks like it has an optimization opportunity (which would give you output you _didn't_ want;) but actually doesn't because of the special case char& or char* can alias anything rule.

#include <stdio.h>

char b[4] = {0,0,0,0};
const short *w;
const int   *d;

int main()
{
    size_t i;
    w = ((short*)b);
    d = ((  int*)b);
    /* the next line makes explicit endianess assumptions */
printf("%02x%02x%02x%02x %04x%04x %08x\n",b[3],b[2],b[1],b[0],w[1],w[0],d[0]);
    for (i=0; i<4; ++i) {
        b[i] = (char)(i+1);
printf("%02x%02x%02x%02x %04x%04x %08x\n",b[3],b[2],b[1],b[0],w[1],w[0],d[0]);
    }
    return 0;
}

A compiler might want to optimize the references to w and d since they're unchanged inside the loop, and just remember their values from outside the list. Unfortunately, since access through a char reference or pointer can alias anything, the compiler is unable to make this assumption and cannot do any optimizations. In general, doing any accesses of things through a char* or char& in a method or function can make a lot of optimizations impossible.

Patrick

p.s. Please read my aliasing whitepaper and make any suggestions for improvement that occur to you. http://dbp-consulting.com/StrictAliasing.pdf


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux