EDIT: To answer your latest comment:
Yes, what I'm looking for was just if there is a compiler option that warns it. If there isn't, maybe I should just code more carefully.
No, in C there unfortunately isn't. Yes, you should code more carefully. In general, I would suggest you to think about why you would want to have such feature. If "protecting" index variables inside loops is a concern, I would first ask myself if my coding style makes sense and is consistent.
As Eric Postpischil noticed, you can just use a temporary variable to shadow your index variable inside an inner block as const
. This way the compiler will error-out if you try to modify it.
This however produces shadowing warnings (in particular with the -Wshadow
flag, which is pretty common):
shadow.c:9:14: warning: declaration of ‘i’ shadows a previous local [-Wshadow]
const int i = t;
^
shadow.c:4:11: note: shadowed declaration is here
for (int i = 0; i < 10; ++i)
To avoid this, you can use simple diagnostic #pragma
directives and temporarily disable the warning for that specific code block:
for (int i = 0; i < 10; ++i)
{
const int t = i;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
{
const int i = t;
printf("i = %d\n", i);
i = 4; // Will yield a compiler error.
}
#pragma GCC diagnostic pop
}
The above code works (removing the i = 4
of course) and compiles without warnings using -Wall -Werror -Wshadow -pedantic
in both GCC and Clang.
NOTE: this surely is no good practice, but AFAICT it's the only way to achieve such behavior in C.