How do I put two increment statements in a C++ 'for' loop?

前端 未结 8 735
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 02:55

I would like to increment two variables in a for-loop condition instead of one.

So something like:

for (int i = 0; i != 5; ++i and ++j)          


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 03:44

    I agree with squelart. Incrementing two variables is bug prone, especially if you only test for one of them.

    This is the readable way to do this:

    int j = 0;
    for(int i = 0; i < 5; ++i) {
        do_something(i, j);
        ++j;
    }
    

    For loops are meant for cases where your loop runs on one increasing/decreasing variable. For any other variable, change it in the loop.

    If you need j to be tied to i, why not leave the original variable as is and add i?

    for(int i = 0; i < 5; ++i) {
        do_something(i,a+i);
    }
    

    If your logic is more complex (for example, you need to actually monitor more than one variable), I'd use a while loop.

提交回复
热议问题