Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does comparing unsigned long with negative number result in false? [duplicate]

Tags:

c++

c++11

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 ?

like image 369
Rahul Iyer Avatar asked Oct 05 '16 11:10

Rahul Iyer


2 Answers

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

like image 67
Treycos Avatar answered Oct 07 '22 21:10

Treycos


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;
}
like image 2
Raindrop7 Avatar answered Oct 07 '22 21:10

Raindrop7