Home > Backend Development > C++ > Why Does Comparing a Negative Integer to an Unsigned Integer in C Yield Unexpected Results?

Why Does Comparing a Negative Integer to an Unsigned Integer in C Yield Unexpected Results?

Linda Hamilton
Release: 2024-12-08 04:34:10
Original
632 people have browsed it

Why Does Comparing a Negative Integer to an Unsigned Integer in C   Yield Unexpected Results?

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";
}
Copy after login

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"
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template