C++ 算术溢出:“operator”运算会导致编译时溢出

文章目录

  • 算术溢出编译报警

算术溢出编译报警

uint64_t sum = 25*1000*1000*1000;

警告:C4307
微软给出了示例

修改前:
int multiply()
{
    const int a = INT_MAX;
    const int b = 2;
    int c = a * b; // C26450 reported here
    return c;
}

修改后:

long long multiply()
{
    const int a = INT_MAX;
    const int b = 2;
    long long c = static_cast<long long>(a) * b; // OK
    return c;
}

但是在Visual Studio中

uint64_t sum = static_cast<uint64_t>(1000*1000*1000*25); //C26450 reported here

正确的写法是:

uint64_t sum = static_cast<uint64_t>(1000 * 1000 * 1000) * 25;

你可能感兴趣的:(C++,c++,开发语言)