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

后端 未结 9 1204
天涯浪人
天涯浪人 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 04:51

    And here is a C++11 version:

    for (int const i : {0,1,2,3,4,5,6,7,8,9,10})
    {
        std::cout << i << " ";
        // i = 42; // error
    }
    

    Here is live demo

提交回复
热议问题