函数 return 类型是无符号的,而它 returns -1 表示错误

Function return type is unsigned while it returns -1 for error

我已经使用 libnet 一段时间了,我注意到有一些函数 return 的值是 uint32_t,据我所知,这是一个无符号类型。但是,在 documentation 中,如果发生错误(它是有符号类型),它会告诉 return -1 参见 libnet_get_ipaddr4libnet_get_prand,例如。

但是,我使用这些函数没有问题:

if ((src_ip_addr = libnet_get_ipaddr4(l)) == -1) { /* treat the failure*/ }

我想比较发生在解释为 unsigned int 的 -1 与取相同值的 return 值之间;比较正确。

尽管这显然有效,但我的问题是:这有意义吗?为什么?作为一个程序员,我应该如何检查return的值来判断是否有错误呢?上面显示的代码片段是否正确?

引用C99标准草案,6.2.5.9:

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

所以-1自动转换为UINT32_MAX

警告: 处理超出范围的值对于 signed 类型来说不是很好。有关各种并发症,请参阅 here and here

6.5.9 表示对于相等运算符,

If both of the operands have arithmetic type, the usual arithmetic conversions are performed.

6.3.1.8 描述了这些转换:

[...] Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type. [...]

(您可以在标准中寻找为返回带符号类型的函数返回 -1 的类似理由,但它基本上是相同的参数,所以我不会打扰。)

换句话说,是的,这是完全正确的。