I tried this on Mac OS and Redhat (g++ 6.3.1), file "test.cpp": g++ -Wall -Wextra -Wconversion -pedantic -o test test.cpp
#include <iostream>
int main()
{
int a = 777;
for (int k = 0; k < 2; ++k) {
a = 111; // external a
int a = 0; // internal a
for (int j = 0; j < 3; ++j) a += j + k;
std::cout << "internal a: " << a << std::endl;
}
std::cout << "external a: " << a << std::endl;
}
Output: internal a: 3 internal a: 6 external a: 111
The question why does it compile? I always thought (20+ years) that scoping rules in C++ are very strict (for good). Apparently two similarly named variables "a" exist in the same scope. The example came from the real code where I made a mistake.