Peter Doerfler wrote:
Erik wrote:
I just installed g++-4.0.3 on a Pentium Mobile. I have a program that
behaves as expected when compiled with -O0 but gives different output
when compiled with -O3. I do not know what to do about it. The
program is called prov. Here is the result of compiling and running it:
$ g++-4.0.3 -O0 -Wall -o prov prov.cc -I/usr/include/SDL && ./prov;
echo $?
1
$ g++-4.0.3 -O3 -Wall -o prov prov.cc -I/usr/include/SDL && ./prov;
echo $?
0
The program looks like this:
______________________________________________________
#include <SDL_types.h>
struct Coords {
bool operator<(const Coords other) const {
return
*reinterpret_cast<const Uint32 * const>(this)
<
*reinterpret_cast<const Uint32 * const>(&other);
}
int x : 16, y : 16;
};
int main() {
Coords a = {0, 1}, b = {1, 0};
return b < a and a < b;
}
______________________________________________________
The operator< is for use with standard containers, so it has to work.
It should of course never happen that b is less than a and a is less
than b, so the program should always return 0. I can see that the
assembly output is very different, but I admitt that I do not
understand much of it. With g++-3.4.5 the program produces identical
output for the different optimization levels.
Why don't you use an anonymous union, like so?
This is exactly what I was looking for. It seems to work great. Many
thanks! Why did I not use it? I was just not smart enough. I tried to
use a union like
union T {
Coords c;
Uint32 i;
};
in the ordering functor, but I had to ditch that idea because it was not
allowed to have a type with constructor in a union. (And Coords has a
constructor, although it was omitted in the sample code here.)
struct Coords {
bool operator<(const Coords other) const;
union {
struct {
int x : 16, y : 16;
};
unsigned int z;
};
};
bool Coords::operator<(const Coords other) const {
return z < other.z;
}