Advertisement
Guest User

Why signed integer overflow sucks

a guest
Jul 14th, 2014
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. // Compile on a recent version of clang and run it:
  2. // clang++ -std=c++11 -O3 -Wall -fsanitize=undefined stdint16.cpp -o stdint16
  3. //
  4. // You'll get a nice error:
  5. // main.cpp:20:55: runtime error: signed integer overflow: 65535 * 65535 cannot be represented in type 'int'
  6. //
  7. // What's just awesome about this is that avoiding this problem portably (i.e.
  8. // without depending upon a particular size of "int") requires a maze of "if"
  9. // or "#if" statements or doing your multiplications using uintmax_t.  Great
  10. // solution, huh? >.<
  11. //
  12.  
  13. #include <cinttypes>
  14. #include <cstdint>
  15. #include <cstdio>
  16.  
  17. int main()
  18. {
  19.      std::uint8_t a =  UINT8_C(              0xFF); a *= a; // OK
  20.     std::uint16_t b = UINT16_C(            0xFFFF); b *= b; // undefined!
  21.     std::uint32_t c = UINT32_C(        0xFFFFFFFF); c *= c; // OK
  22.     std::uint64_t d = UINT64_C(0xFFFFFFFFFFFFFFFF); d *= d; // OK
  23.  
  24.     std::printf("%02" PRIX8 " %04" PRIX16 " %08" PRIX32 " %016" PRIX64 "\n", a, b, c, d);
  25.  
  26.     return 0;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement