Iterating over all unsigned integers in a for loop

前端 未结 6 685
后悔当初
后悔当初 2020-12-07 01:09

Let\'s say I want to iterate over all integers in a for loop. For the sake of discussion, assume I am calling some unknown function f(unsigned x) f

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 01:48

    You'll have to perform the test at the end of the loop body, much like a do-while:

    for (unsigned int i = 0; /* nothing */; i++) {
        ...
        if (i == UINT_MAX) {
            break;
        }
    }
    

    For a test in the standard for loop test position to work, you would need to track the current iteration in a way that can distinguish between UINT_MAX+2 states: one for each time you enter the loop body, and one for the one time you don't. A single unsigned int can't handle that, so you'd need at least one auxiliary variable or a bigger loop counter.

提交回复
热议问题