Recently, I accidentally wrote C code that looks like this:
for (size_t i = 0; i < SOME_VALUE; ++i)
{
for (size_t i = 0; i < ANOTHER_VALUE; ++i)
{
// do work with 'i' from inner loop *WITHOUT* any disruption to 'i' from outer loop
}
}
Reading the code closely, I discovered this "bug". However, at runtime, it did not cause any issues. To be clear, my code was compiled with a relatively recent version of MinGW-w64 to create a native Win32 binary.
Sure, the code works, but I am surprised this is allowed, and even more surprised that my GCC-ish compiler did not complain about it! (Is there a GCC warning option for this mistake?)
Can someone explain why this is allowed, and why the inner and outer i
variables do not conflict / disrupt? Ideally, someone can point me to official ISO-ish C language definition that allows (and supports) this behaviour!
Inspired by: What versions of C allow you to declare variables in for loops?