Consider a standard for loop:
for (int i = 0; i < 10; ++i)
{
// do something with i
}
I want to prevent the variable i
fr
#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
}
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
}
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...)