unsigned long mynum = 7;
if(mynum > -1) // false
Why does this happen ? is it because -1 is an int, and when it gets "promoted" to unsigned long, it gets the maximum value of unsigned long ?
This might not be right but here's what i think:
When you execute the following code
unsigned long a = -8;
std::cout << a;
Since unsigned values can't be below 0, it will return the max value of an unsigned long - 8 or 4294967288 in this case.
And thats what happened to the -1
in your operation when it got converted to an unsigned long
unsigned variables has the maximum value they don't have a minus sign so the last bit is positive.
assigning a negative value to a unsigned will set the value to the corresponding signed value: -1 and 255 has the same bitfield set:
#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;
}
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