daily pastebin goal
56%
SHARE
TWEET

Why signed integer overflow sucks, v2

a guest Jul 14th, 2014 820 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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:21:37: runtime error: signed integer overflow: 65535 * 65535
  6. //     cannot be represented in type 'int'
  7. //
  8. // What's just awesome about this is that avoiding this problem portably (i.e.
  9. // without depending upon a particular size of "int") requires a maze of "if"
  10. // or "#if" statements or doing your multiplications using uintmax_t.  Great
  11. // solution, huh? >.<
  12. //
  13.  
  14. #include <cinttypes>
  15. #include <cstdint>
  16. #include <cstdio>
  17.  
  18. int main()
  19. {
  20.      std::uint8_t a =  UINT8_MAX; a *= a; // OK
  21.     std::uint16_t b = UINT16_MAX; b *= b; // undefined!
  22.     std::uint32_t c = UINT32_MAX; c *= c; // OK
  23.     std::uint64_t d = UINT64_MAX; d *= d; // OK
  24.  
  25.     std::printf("%02" PRIX8 " %04" PRIX16 " %08" PRIX32 " %016" PRIX64 "\n",
  26.         a, b, c, d);
  27.  
  28.     return 0;
  29. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top