开发者

C - is it possible to decrement the max value of a for loop from within the for loop?

for exa开发者_如何转开发mple:

void decrement(int counter) {
    counter--;
}

int counter = 20;
for (int i = 0; i < counter; i++) {
    for (int j = 0; j < counter, j++) {
        decrement(counter);
    }
}

ideally, what i'd like to see is the counter var being decremented every time the for loop is run, so that it runs fewer than 20 iterations. but gdb shows that within decrement() counter is decremented, but that going back to the for loop counter actually stays the same.


Yes it is possible:

for (int i = 0; i < counter; i++) {
    counter--;
}

The reason why it doesn't work in your example is because you are passing by value and modifying the copy of the value. It would work if you passed a pointer to the variable instead of just passing the value.


You can also use pointers so the value remains changed outside of the decrement function:

void decrement(int *counter) {
    (*counter)--;
}

int counter = 20;
for (int i = 0; i < counter; i++) {
    for (int j = 0; j < counter; j++) {
        decrement(&counter);
    }
}

Or just do counter-- instead of calling the decrement function.


As Mark has shown it is possible, but its one of those don't do it

While you can all sorts of tricky things with for loops, its best not to if you can write it in a more clear fashion.

Keep code short for understanding, not code space. Code is for humans to read, not to care about how much space it is taking up. (In the general case anyways)


All you do is simply counter --;, you don't need to do anything special, especially if it adds to the complexity of the code without providing any additional functionality that the language can't already accomodate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜