Search code examples
cfor-loopinfinite-loopunsignedunsigned-integer

Why is this for loop with an unsigned int endless?


for (unsigned i = 0; i < 3; i++) {
    if (i == 2) i = -1;
}

I can't understand why this loop is infinite. I get that it wraps around when i = -1 but UINT_MAX is greater than 3.


Solution

  • If I rewrite your code, then might more clear to see why

    unsigned i = 0;
    while (i < 3) {
        if (i == 2) i = -1;
        i++;
    }
    

    i++ happens at the end of the loop so i became 0 again.