View difference between Paste ID: nLzRGHr0 and c0mTmL2K
SHOW: | | - or go back to the newest paste.
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'
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-
     std::uint8_t a =  UINT8_C(              0xFF); a *= a; // OK
19+
20-
    std::uint16_t b = UINT16_C(            0xFFFF); b *= b; // undefined!
20+
     std::uint8_t a =  UINT8_MAX; a *= a; // OK
21-
    std::uint32_t c = UINT32_C(        0xFFFFFFFF); c *= c; // OK
21+
    std::uint16_t b = UINT16_MAX; b *= b; // undefined!
22-
    std::uint64_t d = UINT64_C(0xFFFFFFFFFFFFFFFF); d *= d; // OK
22+
    std::uint32_t c = UINT32_MAX; c *= c; // OK
23
    std::uint64_t d = UINT64_MAX; d *= d; // OK
24-
    std::printf("%02" PRIX8 " %04" PRIX16 " %08" PRIX32 " %016" PRIX64 "\n", a, b, c, d);
24+
25
    std::printf("%02" PRIX8 " %04" PRIX16 " %08" PRIX32 " %016" PRIX64 "\n",
26
        a, b, c, d);
27
28
    return 0;
29
}