开发者

Confusing C++ global scope issues

开发者 https://www.devze.com 2023-01-28 20:45 出处:网络
I am taking a C++ practice test and I\'m confused with a set of access scope and point of declaration related questions. Both thequestions are related to each other..I know the answers..what i need is

I am taking a C++ practice test and I'm confused with a set of access scope and point of declaration related questions. Both the questions are related to each other..I know the answers..what i need is proper explanation :

What is the value of the local variable x at the end of main

 int x = 5;
 int main(int argc, char** argv)
 {
    int x = x;
    return 0;
 }

ans: Undefined

What is the value of y at the end of main?

    const int x = 5;
    int main(int argc, char** argv)
    {
 开发者_如何学C      int x[x];
       int y = sizeof(x) / sizeof(int);
       return 0;
    }

answer: 5


From the standard: 3.3.1 [basic.scope.pdecl]

The point of declaration for a name is immediately after its complete declarator (clause 8) and before its initializer (if any), except as noted below.

The standard even has two examples to clarify this:

int x = 12;
{ int x = x; }

Here the second x is initialized with its own (indeterminate) value.

[Note: a nonlocal name remains visible up to the point of declaration of the local name that hides it. [Example:

const int i = 2;
{ int i[i]; }

declares a local array of two integers. ]]

These two examples cover the two cases in your question.


It's controlled by when the inner x comes into existence (the start of its scope). The standard states (3.3.1 in the current standard, 3.3.2 in the upcoming one) in part (my italics):

The point of declaration for a name is immediately after its complete declarator and before its initializer.

With int x = x;, it's created at the point of the = so that when you assign x to it, that's the inner x which is being used. Since that hasn't been set to anything before, it's undefined.

With int x[x];, the inner x comes into existence at the ; so it's using the outer x as the array size.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号