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)?
1is anint. The type of an integral arithmetic expression depends on the types involved. In this case, you have anunsignedtype and asignedtype where theunsignedtype is smaller than thesignedtype. This falls under the C++ standard on expressions (section 5.10 [expr]):I.e., the type of the expression
bytesCount + 1isintwhich is signed by default.