Comparisons in C\C++

This tip submitted by Nikitas Angelinas on 2005-12-09 03:44:11. It has been viewed 90593 times.
Rating of 5.8 with 952 votes

Let's say you have something like:
unsigned int u = 10;
int i = -1;

for(i <= u;i++){

/*do whatever here*/

}//end of for

But nothing of what you do in the loop seems to execute, it's because the ANSI C standard defines that whenever there is a comparison between a qualified and a non qualified type, the non qualified type gets promoted to a type of the same type,but also inherits the qualifiers of the other quantity. I'm sure I could have said that better.

Anyway, in other words, i here is promoted to an unsigned int,and so its value (-1), which is coded in two's complement is interpreted as an unsigned int. Now -1 as an unsigned is 00000001 -> 11111110 + 1 = 11111111 i.e. a very large positive number,actually the largest int. Note that I have only used eight digits for the sake of simplicity.Its also very early in the morning and I haven't slept.
So, remember this if you ever perform such a comparison.Qualifier inheritance also occurs with short and long, besides unsigned.

More tips

Help your fellow programmers! Add a tip!