1

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

1 回答 1

3

正如霍尔特所指出的,您实际上是在假设 2 的补码算术。因此,您可以替换-minmax+1

if(result == uint64_t(numeric_limits<int64_t>::max()) + 1)

这避免了在否定最小值时导致的未定义行为(有符号整数溢出)。

验证您的系统是否真的使用 2 的补码可能是个好主意(取决于您希望遵守 C++ 标准的严格程度)。这可以通过比较来-max实现min

if (numeric_limits<int64_t>::max() + numeric_limits<int64_t>::min() == 0)
{
    // If not two's complement:
    // Too large absolute value == error, regardless of sign
    return false;

    // on all sane (2's complement) systems this will be optimized out
}

min和之间没有其他关系的可能性max;这是解释here

于 2015-10-26T11:16:13.587 回答