Unsigned and signed comparison

Here is a very simple code,

#include <iostream>
using namespace std;
int main() {
    unsigned int u=10;
    int i;
    int count=0;
    for (i=-1;i<=u;i++){
        count++;
    }
    cout<<count<<"\n";
    return 0;
}

The value of count is 0. Why?

+5
source share
5 answers

Both operands <=must be converted to the same type.

Obviously, they are upgraded to unsigned int(I do not have a rule from the standard in front of me, I will watch it in a second). Since it (unsigned int)(-1) <= uis false, the loop is never executed.

The rule is found in section 5 (expr) of the standard, paragraph 10, which states (I highlighted the applicable rule):

, , . , , . , :

  • (7.2), ; , .
  • long double, double.
  • , , double.
  • , float, float.
  • (4.5) . 60 :
  • , .
  • , , .
  • , , , .
  • , , .
  • , .
+8

(i <= u), i , -1 UINT_MAX.

unsigned int (UINT_MAX + 1) , -1 UINT_MAX, -2 UINT_MAX - 1 ..

, , , , , signed unsigned. , , unsigned , , . unsigned int ( ) .

+4

, -1 unsigned int, .

-Wall -Wextra, ( g++)

http://en.wikipedia.org/wiki/Two's_complement

+1

, , i . UINT_MAX, 32- 4294967295. , , :

// will never run
for (i = 4294967295; i <= u; i++) {
    count++;
}
+1

, 4 , , -1 2147483649 (1000 0000 0000 0000 0000 0000 0000 0001) - 1 MSB, 1, .

0
source

All Articles