Here is 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 of
<=have to be promoted to the same type.Evidently they are promoted to
unsigned int(I don’t have the rule from the standard in front of me, I’ll look it up in a second). Since(unsigned int)(-1) <= uis false, the loop never executes.The rule is found in section 5 (expr) of the standard, paragraph 10, which states (I’ve highlighted the rule which applies here):