CPP Error: Integer overflow in expression

前端 未结 2 819
甜味超标
甜味超标 2020-12-12 03:21

I\'m trying to represent 16gb in bytes, and uint64_t throws an error.

What kind of data type should I use to represent it? unsigned long int

相关标签:
2条回答
  • 2020-12-12 03:41

    As-is your expression consists of integer literals without suffixes and will be evaluated as a signed integer and the value will overflow. The result of your expression is 17179869184 and the max value the 32-bit integer can hold is 2147483647 so it will overflow. To force the expression to be evaluated as unsigned (unsigned long long in your case) value you should add the ULL or ull suffix to one of your operands (except the final one as pointed out in the comments) so that the entire expression is evaluated as unsigned long long. Trivial example to demonstrate what happens:

    #include <iostream>
    #include <cstdint>
    #include <limits>
    
    int main() {
        uint64_t x; // unsigned long long
        auto y = 16 * 1024 * 1024 * 1024; // evaluated as int, the result overflows
        auto z = 16ull * 1024 * 1024 * 1024; // evaluated as unsigned long long, does not overflow
        std::cout << "Your expression: " << z << '\n';
        std::cout << "Maximum integer value: " << std::numeric_limits<int>::max() << '\n';
        std::cout << "Maximum unsigned long long value: " << std::numeric_limits<unsigned long long>::max() << '\n';
        x = z;
    }
    
    0 讨论(0)
  • 2020-12-12 03:47

    uint64_t TESTBYTES = 16ULL * 1024 * 1024 * 1024 will do it.

    Else the expression 16 * 1024 * 1024 * 1024 is evaluated as an int, with undefined results on your platform since you are overflowing the int type.

    ULL promotes the first term to an unsigned long long, forcing promotion of the other terms. This is always safe singe an unsigned long long needs to be at least 64 bits.

    0 讨论(0)
提交回复
热议问题