Home >Backend Development >C++ >How Does C Handle Comparisons Between Signed and Unsigned Integers?
In C , when comparing a signed integer with an unsigned integer, the signed integer is promoted to an unsigned integer. This means that the negative sign is ignored and the integer is treated as a large positive value.
Consider the following C program:
#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"; }
In this program, the size of the vector a is an unsigned integer. However, when comparing it to the signed integer b, b is promoted to an unsigned integer. This means that the negative sign is ignored and b is treated as a large positive value. Therefore, the comparison b < a.size() will always be false, and the program will print "Greater."
To see this behavior more clearly, consider the following code sample:
#include <iostream> int main() { unsigned int a = 0; int b = -1; std::cout << std::boolalpha; std::cout << (b < a) << "\n"; }
This program will output false, even though b is obviously less than a. This is because b is promoted to an unsigned integer, and the negative sign is ignored.
The above is the detailed content of How Does C Handle Comparisons Between Signed and Unsigned Integers?. For more information, please follow other related articles on the PHP Chinese website!