Search code examples
ccastingintegertypecheckingsize-t

why size_t variable, int constant comparison doesn't work properly while off_t variable works fine?


I was trying to compare size_t(long int type for ubuntu) variable with int constant 0 but turned out not working properly. but off_t variable works fine.

size_t var = -3;

if(var < 0)
    putchar('X');
else
    putchar('Y');

// Y

but when I cast var into int, it works as I expect.

size_t var = -3;

if((int)var < 0)
    putchar('X');
else
    putchar('Y');

// X

but off_t(long int as well on my ubuntu) works fine without casting.

off_t var2 = -3;

if(var2 < 0)
    putchar('X');
else
    putchar('Y');

// X

Could you explain this please? Thanks.


Solution

  • The type size_t is an unsigned type. So when you attempt to assign the value -3 to it, the value gets converted into a very large positive value. This is why the condition in the first case is false.

    In the second case, when casting var to an int, the assigned value (i.e. the very large positive value from before) is outside the range of int so it gets converted in an implementation defined manner. On most implementations, this will result the value being converted to -3, so the condition will be true.

    The type off_t is a signed type so it is able to store the value -3, so the comparison works as expected.