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?
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.
unsigned int
(unsigned int)(-1) <= u
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 :, ., , ., , , ., , ., .
, , . , , . , :
(i <= u), i , -1 UINT_MAX.
(i <= u)
i
unsigned int (UINT_MAX + 1) , -1 UINT_MAX, -2 UINT_MAX - 1 ..
, , , , , signed unsigned. , , unsigned , , . unsigned int ( ) .
, -1 unsigned int, .
-Wall -Wextra, ( g++)
http://en.wikipedia.org/wiki/Two's_complement
, , i . UINT_MAX, 32- 4294967295. , , :
UINT_MAX
4294967295
// will never run for (i = 4294967295; i <= u; i++) { count++; }
, 4 , , -1 2147483649 (1000 0000 0000 0000 0000 0000 0000 0001) - 1 MSB, 1, .