Skip to content

Instantly share code, notes, and snippets.

@sagz
Created April 15, 2014 17:50
Show Gist options
  • Save sagz/10752310 to your computer and use it in GitHub Desktop.
Save sagz/10752310 to your computer and use it in GitHub Desktop.
Compiler bug?
#include <iostream>
template<class Out> Out negate(unsigned long in) {
// This line casts an unsigned long to a signed long.
// 2^63 as an unsigned long is 0x8000000000000000
// Casting 2^63 from unsigned long to signed long should
// produce -2^63 (which is also 0x8000000000000000).
// The twos complement of -2^63 just happens to be -2^63,
// so, (long)(2^63) should always be -2^63, correct?
Out out = -Out(in);
if (out > 0) {
std::cout << "Oops!" << std::endl;
} else {
std::cout << "Correct." << std::endl;
}
return out;
}
int main() {
unsigned long in = 9223372036854775808UL;
std::cout << "Attempt 3: " << std::endl;
negate<long>(in);
}
$ cd ~/Downloads/
[s@lawn.gatech.edu Tue Apr 15, 13:44:27 1289 ~/Downloads]
$ g++ bug_take3.cpp
[s@lawn.gatech.edu Tue Apr 15, 13:44:39 1290 ~/Downloads]
$ ./a.out
Attempt 3:
Correct.
[s@lawn.gatech.edu Tue Apr 15, 13:45:58 1291 ~/Downloads]
$ g++ -O0 bug_take3.cpp
[s@lawn.gatech.edu Tue Apr 15, 13:46:08 1292 ~/Downloads]
$ ./a.out
Attempt 3:
Correct.
[s@lawn.gatech.edu Tue Apr 15, 13:46:10 1293 ~/Downloads]
$ g++ -O2 bug_take3.cpp
[s@lawn.gatech.edu Tue Apr 15, 13:46:15 1294 ~/Downloads]
$ ./a.out
Attempt 3:
Oops!
[s@lawn.gatech.edu Tue Apr 15, 13:46:17 1295 ~/Downloads]
$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.1.0
Thread model: posix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment