The sum of signed and unsigned is unsigned in C++

#include <iostream>

template <typename T>
void PrintValue(T val)
{
    if constexpr (std::is_signed_v<T>)
    {
        std::cout << "signed";
    }
    else
    {
        std::cout << "unsigned";
    }

    std::cout << std::endl << val << std::endl;
}
int main()
{
    int a = -1;
    unsigned int b = 5;
    unsigned int c = 7;
    
    auto sum = b + a;
    
    PrintValue(sum);

    PrintValue(c - b);
    PrintValue(b - c);
}

The output is:

unsigned
4
unsigned
2
unsigned
4294967294

As you can see, the sum of signed and unsigned values is unsigned and the difference of two unsigned values is unsigned.

Leave a Reply

Your email address will not be published. Required fields are marked *