0

Possible Duplicate:
Unsigned and signed comparison
unsigned int and signed char comparison

I have a strange behavior when i try to enter in this while statement:

unsigned u = 0;
int i = -2;

while(i < u)
{
    // Do something
    i++;
}

But it never enters, even if when i set a break point i = -2 and u = 0. What am I doing wrong? How could i fix this?

Community
  • 1
  • 1
Nick
  • 10,309
  • 21
  • 97
  • 201

2 Answers2

6

It's because the ANSI C standard defines that whenever there is a comparison between a qualified (your unsigned int u) and a non qualified type (your int i), the non qualified type gets promoted to a type of the same type (thus always int), but also inherits the qualifiers of the other quantity (i.e. it becomes unsigned).

When your int, whose value is equal to -2, becames unsigned the first byte undergoes this transformation: 0000 0010 -> 1111 1110. Your int is now a very large positive number, certainly larger of your unsigned int.

There is a solution: cast to signed

while(i < (signed) u)
{
    // Do something
    i++;
}

By the way, probably your compiler should give you a warning.

gliderkite
  • 8,828
  • 6
  • 44
  • 80
  • Thanks, +1 for the solution with a complete explanation. – Nick Jun 01 '12 at 12:07
  • Would it work if you defined i as ```signed int i```? – Alex Chamberlain Jun 01 '12 at 12:15
  • By default, if we do not specify either `signed` or `unsigned` most compiler settings will assume the type to be signed, so in this case `signed int i` has the same effect of `int i` and the result is the same. – gliderkite Jun 01 '12 at 12:27
  • @gliderkite: Are you sure? In C "qualified types" are e.g. `const int`, `volatile char`. `unsigned`/`signed` are not qualifiers (but type specifiers). Then there is: `unsigned a; signed int b; a < b;` where b is converted to `unsigned int`. **All** C compilers will assume a signed type because this is what the standard defines (except for `char`). – undur_gongor Jun 01 '12 at 12:32
  • 1
    Your vocabulary and description are just wrong. "qualified" in the standard refers to `const` and `volatile`. What is going on here is something more subtle, namely implicit conversion. And the rules for that are not so direct as you suggest. I suggest that you delete your answer. – Jens Gustedt Jun 01 '12 at 12:33
  • @undur_gongor You can read it yourself [here](http://www.cplusplus.com/doc/tutorial/variables/) – gliderkite Jun 01 '12 at 12:34
  • @gliderkite: This is about C++. The question is about C. Maybe that page is even wrong/incorrect for C++ too. – undur_gongor Jun 01 '12 at 12:36
2

You are comparing a signed and unsigned integer and your problems started there...
Don't do that and it should work just fine.

Alok Save
  • 202,538
  • 53
  • 430
  • 533