Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why local variable doesn't hide the global variable in array definition

Tags:

c++

I am reviewing subtle points in C++ these days. I found an interesting question. Could you please check it and share your reasoning why it works like that.

Thank you

const int x = 5;

void func() {
    // ! Error    
    // int x = x;

    // ! Fine    
    int x[x];
    x[0] = 12;
    cout << x[0];
}
like image 330
Validus Oculus Avatar asked Mar 16 '23 22:03

Validus Oculus


1 Answers

The point of declaration for a variable (that is, the point at which the name assumes the meaning given to it by the declaration, hiding any other entities with the same name in a wider scope) comes after the declarator, and before any initialiser. So this:

int x = x;
     ^ point of declaration

initialises the local variable x with its own uninitialised value, giving undefined behaviour (although it's still well-formed, so the compiler shouldn't reject it unless you ask it to).

While this:

int x[x];
        ^ point of declaration

uses the global constant x within the declarator, which is well-formed and well-defined. It's potentially baffling for human readers, but no problem for the compiler.

The rationale for this rule is that it's reasonable to use the address (but not the value) of a variable in its own initialiser, a simple example being

void * p = &p;
like image 75
Mike Seymour Avatar answered Apr 09 '23 00:04

Mike Seymour