Home >Backend Development >C++ >How Does C Handle Comparisons Between Signed and Unsigned Integers?

How Does C Handle Comparisons Between Signed and Unsigned Integers?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 00:16:11999browse

How Does C   Handle Comparisons Between Signed and Unsigned Integers?

Comparison of Signed and Unsigned Types in C

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!

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