CPP Error: Integer overflow in expression

前端 未结 2 835
甜味超标
甜味超标 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 
    #include 
    #include 
    
    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::max() << '\n';
        std::cout << "Maximum unsigned long long value: " << std::numeric_limits::max() << '\n';
        x = z;
    }
    

提交回复
热议问题