Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Compile on a recent version of clang and run it:
- // clang++ -std=c++11 -O3 -Wall -fsanitize=undefined stdint16.cpp -o stdint16
- //
- // You'll get a nice error:
- // main.cpp:20:55: runtime error: signed integer overflow: 65535 * 65535 cannot be represented in type 'int'
- //
- // What's just awesome about this is that avoiding this problem portably (i.e.
- // without depending upon a particular size of "int") requires a maze of "if"
- // or "#if" statements or doing your multiplications using uintmax_t. Great
- // solution, huh? >.<
- //
- #include <cinttypes>
- #include <cstdint>
- #include <cstdio>
- int main()
- {
- std::uint8_t a = UINT8_C( 0xFF); a *= a; // OK
- std::uint16_t b = UINT16_C( 0xFFFF); b *= b; // undefined!
- std::uint32_t c = UINT32_C( 0xFFFFFFFF); c *= c; // OK
- std::uint64_t d = UINT64_C(0xFFFFFFFFFFFFFFFF); d *= d; // OK
- std::printf("%02" PRIX8 " %04" PRIX16 " %08" PRIX32 " %016" PRIX64 "\n", a, b, c, d);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement