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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With