syntax highlight

Tuesday 31 March 2015

Scope ending in C++

Is the following code valid C++?

const int x = 42;
void f() {
    int x[x];
    x[24] = 0;
}

Unfortunately, it is. According to 3.3.2 in the standard, a definition is available in a child scope up to the point where it's shadowed, and that means "x" will first be interpreted as the global const int, being an index for a vector named "x". Any new references to "x" will point to the new declaration.

Fun stuff, right?