strict aliasing rule and examples

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

 



hello,
i've just encountered some code breaking the aliasing rule:

#include <cstdio>

unsigned EndianSwap (unsigned data) {
    return (data << 24 & 0xff000000) | (data << 8 & 0x00ff0000)
        | (data >> 8 & 0x0000ff00) | (data >> 24 & 0x000000ff);
}
float EndianSwap (float data) {
    unsigned res = EndianSwap(*reinterpret_cast<const unsigned *>(&data));
    return *reinterpret_cast<float*>(&res);
}
int main () {
    float aa = 123.456f;
    float bb = EndianSwap(aa);
    printf("swap: %f -> %f\n", aa, bb);
}

the thing is that i can see what happens if -O3 and -fstrict-aliasing
is on, but i'd like to know what's going on under-the-hood (if it is
almost-human explainable):
i mean - what is compiler doing to optimize the whole swap code out?


and yet another (perhaps related) thing: let's have following code:

struct vect {
  float x, y, z;
  float & operator[] (int i) { return *(&x + i); }
};

i know that there is a potential hazard with padding, but
gcc guru of mine told me that this is in fact breaking of the aliasing
rule too, but after few beers i stopped following his arguments.
is it? how does it break the rule? or is this code dangerous in any
other way?

thanks for your attention,
mojmir

[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