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 ?
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;
}
This is because of implicit typecast
which is performed internally by compiler.
When the operation is going between two different types of variables the compiler itself typecasts (converts temporarily) the lower data type to higher datatype temporarily.
Here in your code -1
temporarily acts as unsigned long
because implicit typecasting performed by compiler itself. It behaves as unsigned long
because the other variable is pf that type.
here -1 is not treated as -1
but its treated as its equivalent as unsigned long
.