3

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
Jagdish
  • 1,848
  • 3
  • 22
  • 33
  • 3
    Look at the type promotion rules in C when unlike types are compared or involved in operations together. When you compare `i == -1`, the value `-`1` is cast to unsigned, and then it's compared. In this case, `-1` becomes `0xFFFFFFFF` and then matches `i`. – lurker Aug 08 '15 at 20:18
  • 1
    Section 6.3.1.8, Usual arithmetic conversions, of C99 described at http://stackoverflow.com/questions/5087992/unsigned-int-and-signed-char-comparison. – jarmod Aug 08 '15 at 20:20
  • There is a good answer to the question in the following post http://stackoverflow.com/questions/1863153/why-unsigned-int-0xffffffff-is-equal-to-int-1 – BJU Aug 08 '15 at 20:21
  • 1
    If, (and you should), compile with warnings enabled (e.g. `-Wall -Wextra`), you will be warned at compile time of the comparison between signed/unsigned types. You have just found the reason for the warnings. Heed them... – David C. Rankin Aug 08 '15 at 20:24

2 Answers2

2

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.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
1

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.

Daniel Jour
  • 15,896
  • 2
  • 36
  • 63