Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned variable is behaving like signed [duplicate]

Tags:

c

linux

gcc

This is the code,

#include <stdio.h>                                                                                                                     
int main()
{
    unsigned int i = 0xFFFFFFFF;
    if (i == -1)
        printf("signed variable\n");
    else
        printf("unsigned variable\n");
    return 0;
}

This is the output,

signed variable

Why is i's value -1 even it is declared as unsigned? Is it something related to implicit type conversations?

This is the build environment,

Ubuntu 14.04, GCC 4.8.2
like image 823
Jagdish Avatar asked Jun 21 '26 02:06

Jagdish


2 Answers

The == operator causes its operands to be promoted to a common type according to C's promotion rules. Converting -1 to unsigned yields UINT_MAX.

like image 139
R.. GitHub STOP HELPING ICE Avatar answered Jun 22 '26 16:06

R.. GitHub STOP HELPING ICE


i's value is 0xFFFFFFFF, which is exactly the same as -1, at least when the later is converted to an unsigned integer. And this is exactly what is happening with the comparison operators:

If both of the operands have arithmetic type, the usual arithmetic conversions are performed. [...]

[N1570 $6.5.9/4]

-1 in two's complement is "all bits set", which is also what 0xFFFFFFFF for an unsigned int (of size 4) is.

like image 24
Daniel Jour Avatar answered Jun 22 '26 15:06

Daniel Jour