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

Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190

3 Answers3

3

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

Treycos
  • 7,373
  • 3
  • 24
  • 47
3

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;
}
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
3

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.

Stubborn
  • 780
  • 1
  • 5
  • 20