比较有符号和无符号整数安全吗?

Is comparing signed and unsigned integer safe?

在此代码示例中使用 int 而不是 std::size_t

std::vector<int> v {1,2,3,4};
for(int i = 0; i < v.size(); i++)
{
  std::cout << v[i] << " ";
}

编译器生成以下警告:

warning: comparison between signed and unsigned integer expressions

但是程序按预期运行并输出:

1 2 3 4

我也经常在我从事的项目中注意到这些警告,这些警告已投入生产 运行 年,而且这些警告从未给我们的客户带来任何问题。由于显然那些程序在比较有符号和无符号整数时没有问题,我想问一下:

在您开始比较负数之前是安全的。

Unsigned integer can hold twice as much as normal int, but can't hold negative values.

比较无符号和有符号可以有严重的问题,例如

std::string( "Bah" ).size() < -5

…永远是真的。

这就是您收到警告的原因,但编译器不够聪明,在它分配的时间范围内,无法看到任何特定的此类比较都是安全的。

现在开始你的要点问题。

is there any benefit, performance or safety-wise, to always using unsigned over signed integers where applicable?

是的,为了正确性,避免了 UB。 但是,“适用”是你做位级别事情的地方。对于数字总是喜欢有符号整数或浮点类型。

in what cases, if any, comparing signed and unsigned integer can result in errors or unexpected behavior?

当涉及无符号回绕时,通常是通过隐式将操作数从有符号提升为无符号。

if there is no good reason to worry about those warnings, is there any historical reason, why this information could be useful to developers in the past?

不适用。