C ++: signature / unsigned mismatch when using unsigned types

When I try to compile the following program in C ++ using the Visual Studio 2010 C ++ compiler (X86) with the warning level / W 4 enabled, I get a warning about a mismatch with the signature / unsigned in the marked line.

#include <cstdio>
#include <cstdint>
#include <cstddef>

int main(int argc, char **argv)
{
    size_t idx = 42;
    uint8_t bytesCount = 20;

    // warning C4389: '==' : signed/unsigned mismatch
    if (bytesCount + 1 == idx)
    {
        printf("Hello World\n");
    }

    // no warning
    if (bytesCount == idx)
    {
        printf("Hello World\n");
    }
}

This bothers me as I only use unsigned types. Since comparison

bytesCount == idx

doesn’t cause such a warning, probably this is due to some strange implicit conversation that is taking place here.

Thus: what is the reason why I receive this warning and by what rules does this conversation occur (if this is the reason)?

+5
source share
4

1 int. . unsigned signed, unsigned , signed. ++ ( 5.10 [expr]):

, , .

I.e., bytesCount + 1 int, .

+5

1 - . bytesCount + 1U.

, , - (bytesCount + 1)

+9

1 int, bytesCount + 1 int ().

, int, int, + bytesCount bytesCount + bytesCount int, uint8_t (while bytesCount + 1U unsigned int, , int).

true .

#include <iostream>

int main() 
{
    unsigned short s = 1;
    std::cout << (&typeid( s + 1U ) == &typeid(1U)) << std::endl;
    std::cout << (&typeid( + s ) == &typeid(1)) << std::endl;
    std::cout << (&typeid( s + s ) == &typeid(1)) << std::endl;
}
+3

, bytesCount + 1 signed int. , bytesCount == idx, bytesCount signed int. signed int, unsigned int. , , , . signed int bytesCount . bytesCount + 1 , , , .

+1

All Articles