Why does comparing unsigned long with a negative number result in false?

unsigned long mynum = 7; if(mynum > -1) // false 

Why is this happening? is it because -1 is int, and when it gets "promoted" to unsigned long, does it get the maximum value of unsigned long?

+5
source share
3 answers

This may be wrong, but here is what I think:
When you execute the following code

 unsigned long a = -8; std::cout << a; 

Since unsigned values ​​cannot be lower than 0, it will return the maximum unsigned long value - 8 or 4294967288 in this case.
And this is what happened to -1 in your operation when it was converted to unsigned long

+2
source

unsigned variables has a maximum value that does not have a minus sign, so the last bit is positive.

assigning a negative value to an unsigned sign will set the value to the corresponding signed value: -1 and 255 has the same bit field:

 #include <iostream> int main() { unsigned char uc1 = 255; // 11111111 unsigned char uc2 = -1; //signed : -1 : 11111111 : 1 1111111 : -128 + 127 //unsigned: 255: 11111111 : 1 1111111 : 128 + 127 if(uc1 == uc2) std::cout << "uc1 = uc2" << std::endl; return 0; } 
+2
source

This is because of the implicit typecast that is executed internally by the compiler.

When an operation occurs between two different types of variables, the compiler itself (temporarily converts) the lower data type to the higher data type.

Here in your code, -1 temporarily acts like an unsigned long , because implicit typecasting is done by the compiler itself. It behaves like an unsigned long , because the other variable is pf.

here -1 is not considered as -1 , but it is treated as its equivalent as an unsigned long .

+2
source

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


All Articles