Casting bug in g++ llvm 4.2 int to double

Alec Jacobson

July 02, 2012

weblog/

The following code seems to compile incorrectly using g++, llvm version 4.3 with -O3:
#include <iostream>

int main(int argc,char * argv[])
{
  using namespace std;
  // loop over canonical view quaternions
  for(int sign = -1;sign<=1;sign+=2)
  {
    std::cout<<sign<<" --> "<<(double)sign<<std::endl;
    // Necessary to reproduce bug
    for(int i = 0; i<1; i++)
    {
      for(int j = 0;j<1;j++)
      {
      }
    }
  }
  return 0;
}
For some reason it is not casting the int, rather it seems to be just reinterpreting the bits as a double. Switching off compile optimization, switching to plain old g++ or switching to float instead of double works, but are not helpful in my case. Instead I did something that works, but is likely non-optimal, I replaced the double cast with a float cast followed by a double cast.
(double)(float)sign