unary minus operator applied to unsigned type, result still unsigned
Unsigned types can hold only non-negative values, so unary minus (negation) does not usually make sense when applied to an unsigned type. Both the operand and the result are non-negative.
Practically, this occurs when the programmer is trying to express the minimum integer value, which is -2147483648. This value cannot be written as -2147483648 because the expression is processed in two stages:
The unsigned type of the result can cause unexpected behavior. If the result is used in a comparsion, then an unsigned comparison might be used, for example, when the other operand is an int. This explains why the example program below prints just one line.
The expected second line, 1 is greater than the most negative int
, is not printed because
is false.((unsigned int)1) > 2147483648
You can avoid C4146 by using MIN_INT from Limits.h, which has the type signed int.
The following sample generates C4146:
#include <stdio.h> void check(int i) { if (i > -2147483648) // C4146 printf("%d is greater than the most negative int\n", i); } void main() { check(-100); check(1); }