Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Signed/unsigned mismatch when only using unsigned types

When I try to compile the following C++ program using the Visual Studio 2010 C++ compiler (X86) with warning level /W4 enabled, I get a signed/unsigned mismatch warning at 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 confuses me, since I'm only using unsigned types. Since the comparison

bytesCount == idx

causes no such warning, it probably has to do with some strange implicit conversation that happens here.

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

like image 611
Nubok Avatar asked Dec 19 '11 19:12

Nubok


2 Answers

1 is a signed literal. Try bytesCount + 1U.

The compiler is probably creating a temporary value of the signed type due to the addition of signed and unsigned values ( bytesCount + 1 )

like image 182
patros Avatar answered Nov 18 '22 02:11

patros


1 is an int. The type of an integral arithmetic expression depends on the types involved. In this case, you have an unsigned type and a signed type where the unsigned type is smaller than the signed type. This falls under the C++ standard on expressions (section 5.10 [expr]):

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.

I.e., the type of the expression bytesCount + 1 is int which is signed by default.

like image 32
MSN Avatar answered Nov 18 '22 02:11

MSN