简体   繁体   English

为什么 c++ assert() 在将负 int 与 unsigned int 进行比较时会错误地调用 abort()?

[英]Why does c++ assert() falsely call abort() when comparing a negative int to an unsigned int?

I have found in my c++ program that assert() calls abort() in a case similiar to the following code snippet:我在我的 c++ 程序中发现 assert() 在类似于以下代码片段的情况下调用 abort():

int a = -1;
unsigned int b = 5;

assert(a < b);

As a human I can tell that -1 is definitely smaller than 5, regardless of the fact that one is an int and the other an unsigned int.作为一个人,我可以说 -1 肯定小于 5,不管一个是 int 而另一个是 unsigned int。 Why can't the compiler?为什么编译器不能?

I have already found the solution, which is that this assert is just nonsensical since an unsigned will always be positive (I had kind of forgotten that the variable in my actual code was an unsigned), but I am just curious as to why this happens.我已经找到了解决方案,这个断言是荒谬的,因为无符号的总是正数(我有点忘记了我实际代码中的变量是无符号的),但我很好奇为什么会这样.

When you compare a signed integer with an unsigned integer, the compiler implicitly converts the signed value into unsigned, so essentially:当您将带符号的 integer 与无符号的 integer 进行比较时,编译器会隐式地将有符号值转换为无符号值,因此本质上:

int a = -1;
unsigned int b = 5;

assert(a < b);

is equivalent to:相当于:

assert(static_cast<unsigned>(-1) < static_cast<unsigned>(5));

Now, because unsigned integers cannot hold negative values, -1 wraps up back to UINT_MAX due to integer overflow :现在,因为无符号整数不能保存负值, -1由于integer 溢出而返回到UINT_MAX

assert(UINT_MAX < static_cast<unsigned>(5));

which is obviously false, since UINT_MAX is larger than 5, so the assertion fails.这显然是错误的,因为UINT_MAX大于 5,所以断言失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM