Why is unsigned 4 not considered more than signed -2?

unsigned int x = 4;
int y = -2; 
int z = x > y; 

When implementing this operation, the value of the variable Z is 0, but why is it equal to 0, and not 1 ?.

+4
source share
3 answers

Believe it or not, if the expression C is formed of two arguments, one with a type intand the other with a type unsigned, then the value intwill be raised to a type unsignedfor comparison.

So, in your case y, the type is assigned unsigned. Since it is negative, it will be transformed by adding to it UINT_MAX + 1, and it will take on value UINT_MAX - 1.

Therefore, there x > ywill be 0.

, . . : , gcc, -Wextra, .

+6

.

x > y int unsigned int. y unsigned int, y , unsigned int.

6.3.1.8 C-, , :

, , . , . , , , . , , , , .

...

, , , , .

, y x, 4. x , x > y false, 0.

+2

.

int z = x > y; 

( > ) signed int unsigned int. y unsigned int. -2 unsigned int, -2 -2 + UINT_MAX+1.

C11 6.3.1.3, 2:

, , , , .

So, the program prints 0, because UINT_MAXno less 4.

or

If you want to print 1, make an explicit case type. as:

int z =  (int)x >y; 
+1
source

Source: https://habr.com/ru/post/1689450/


All Articles