unsigned int x = 4;
int y = -2;
int z = x > y;
When realizing this operation the value for the variable Z is 0, but why it is 0 and not 1?.
Believe it or not, if a C expression is formed from two arguments, one with an int
type and the other with an unsigned
type, then the int
value is promoted to an unsigned
type prior to the comparison taking place.
So in your case, y
is promoted to an unsigned
type. Because it's negative, it will be converted by having UINT_MAX + 1
added to it, and it will assume a value UINT_MAX - 1
.
Therefore x > y
will be 0.
Yes, this is the cause of very many bugs. Even professional programmers fall for this from time to time. Some compilers can warn you: for example, with gcc, if you compile with -Wextra
you will get a warning.
This is a result of arithmetic conversions.
In the expression x > y
, you have one int
operand and one unsigned int
operand. y
is promoted to unsigned int
, and the value converted by adding one more than the maximum unsigned int
value to the value of y
.
Section 6.3.1.8 of the C standard covering arithmetic conversions states the following:
Many operators that expect operands of arithmetic type cause conversions and yield result types in a similar way. The purpose is to determine a common real type for the operands and result. For the specified operands, each operand is converted, without change of type domain, to a type whose corresponding real type is the common real type. Unless explicitly stated otherwise, the common real type is also the corresponding real type of the result, whose type domain is the type domain of the operands if they are the same, and complex otherwise. This pattern is called the usual arithmetic conversions
...
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
So now y
is a very large value being compared against x
which is 4. Since x
is smaller than this value, x > y
evaluates to false, which has a value of 0.
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