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

后端 未结 9 1159
天涯浪人
天涯浪人 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:09
    #include <cstdio>
      
    #define protect(var) \
      auto &var ## _ref = var; \
      const auto &var = var ## _ref
    
    int main()
    {
      for (int i = 0; i < 10; ++i) 
      {
        {
          protect(i);
          // do something with i
          //
          printf("%d\n", i);
          i = 42; // error!! remove this and it compiles.
        }
      }
    }
    

    Note: we need to nest the scope because of an astonishing stupidity in the language: the variable declared in the for(...) header is considered to be at the same nesting level as variables declared in the {...} compound statement. This means that, for instance:

    for (int i = ...)
    {
      int i = 42; // error: i redeclared in same scope
    }
    

    What? Didn't we just open a curly brace? Moreover, it's inconsistent:

    void fun(int i)
    {
      int i = 42; // OK
    }
    
    0 讨论(0)
  • 2020-12-24 05:11

    Couldn't you just move some or all the content of your for loop in a function that accepts i as a const?

    Its less optimal than some solutions proposed, but if possible this is quite simple to do.

    Edit: Just an example as I tend to be unclear.

    for (int i = 0; i < 10; ++i) 
    {
       looper( i );
    }
    
    void looper ( const int v )
    {
        // do your thing here
    }
    
    0 讨论(0)
  • 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...)

    0 讨论(0)
提交回复
热议问题