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?.
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.
It is called integer promotion.
int z = x > y;
In this example, the comparison(>) operator operates on a signed int
and an unsigned int
. By the conversion rules, y
is converted to an unsigned int. Because -2
cannot be represented as an unsigned int value, the -2
is converted to -2 + UINT_MAX+1
.
C11 6.3.1.3, paragraph 2:
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
So, the program prints 0
because UINT_MAX
is not less than 4
.
Or
If you want to print 1, then do explicit type case. like:
int z = (int)x >y;