简体   繁体   中英

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:

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. 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:

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 :

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

which is obviously false, since UINT_MAX is larger than 5, so the assertion fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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