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?

2 comments:

  1. It's issues like this that make me recommend enabling warnings of shadow variables, if your compiler supports it (https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md#compilers)

    ReplyDelete
  2. This weird construct actually has a good reason to be, as someone pointed out to me in twitter, namely to be used when writing constructors. So, while it has some reasonable use cases it can also be abused in amusing and unexpected ways. And indeed we should rely in our tools to let us know when we do this kind of things.

    ReplyDelete