Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing C++ global scope issues

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)
    {
       int x[x];
       int y = sizeof(x) / sizeof(int);
       return 0;
    }

answer: 5

like image 305
maxpayne Avatar asked Dec 03 '10 08:12

maxpayne


2 Answers

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.

like image 170
CB Bailey Avatar answered Sep 30 '22 09:09

CB Bailey


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.

like image 37
paxdiablo Avatar answered Sep 30 '22 08:09

paxdiablo