Unsigned and signed comparison

后端 未结 5 1861
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 21:40

Here is very simple code,

#include 
using namespace std;
int main() {
    unsigned int u=10;
    int i;
    int count=0;
    for (i=-1;i<=         


        
5条回答
  •  有刺的猬
    2020-11-27 22:35

    This is because i is promoted to an unsigned value before comparison. This will set it to the value of UINT_MAX, which on a 32 bit machine equals to 4294967295. So your loop is essentially the same as:

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

提交回复
热议问题