Negative Comparison to Positive Unsigned Int?
In C , we often encounter situations where values of different types are compared. However, understanding how these comparisons behave can be tricky.
Consider this code:
#include <iostream> #include <vector> int main() { std::vector<int> a; std::cout << "vector size " << a.size() << std::endl; int b = -1; if (b < a.size()) std::cout << "Less"; else std::cout << "Greater"; }
The code prints "Greater," even though "-1" is clearly less than "0." Why is this happening?
The key lies in the different data types involved. a.size() returns an unsigned integer, while b is a negative signed integer. When comparing these two types, the negative signed integer is promoted to an unsigned integer. This results in a large unsigned value being compared to 0, which is obviously greater.
To illustrate this further, let's look at the following example:
#include <iostream> int main() { std::cout << std::boolalpha; unsigned int a = 0; int b = -1; std::cout << (b < a) << "\n"; // prints "false" }
In this case, the result is "false," as expected. This is because both a and b are promoted to unsigned integers, and "-1" is now a large unsigned value that is greater than 0.
The above is the detailed content of Why Does Comparing a Negative Integer to an Unsigned Integer in C Yield Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!