Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is unsigned 4 not considered greater than signed -2? [duplicate]

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?.

like image 298
J.Doe Avatar asked Dec 23 '22 12:12

J.Doe


2 Answers

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.

like image 51
Bathsheba Avatar answered Dec 28 '22 11:12

Bathsheba


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.

like image 44
dbush Avatar answered Dec 28 '22 10:12

dbush