How to make a for loop variable const with the exception of the increment statement?

后端 未结 9 1212
天涯浪人
天涯浪人 2020-12-24 04:26

Consider a standard for loop:

for (int i = 0; i < 10; ++i) 
{
   // do something with i
}

I want to prevent the variable i fr

9条回答
  •  梦谈多话
    2020-12-24 05:12

    The KISS version...

    for (int _i = 0; _i < 10; ++_i) {
        const int i = _i;
    
        // use i here
    }
    

    If your use case is just to prevent accidental modification of the loop index then this should make such a bug obvious. (If you want to prevent intentional modification, well, good luck...)

提交回复
热议问题