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)?
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 )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With