考虑符号 (+1
或-1
) 是已知的,并且有一个解析无符号整数的代码。该无符号整数可以等于-numeric_limits<int64_t>::max()
。如何在不触发未定义行为的情况下正确比较?
int8_t sign = /* +1 or -1 */;
uint64_t result = /* parse the remaining string as unsigned integer */;
if( result > uint64_t(numeric_limits<int64_t>::max()))
{
if(sign == 1) return false; // error: out of range for int64_t
// Is the below code correct or how to implement correctly its intent?
if(result == uint64_t(-numeric_limits<int64_t>::min()))
{
return true;
}
return false;
}