符号 (+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;
}