1
$\begingroup$

I'm having a hard time understanding this question. Can each declaration have more than one scope or can a declaration have more than one scope?

enter image description here

If it's the later it would be:

Declaration              Scope
int a = 1;               B1  
int b = 1;               B1
int b = 2;               B2
int a = 3;               B3
int b = 4;               B4

Or can it have more than one scope:

Declaration              Scope
int a = 1;               B1, B2, B4  
int b = 1;               B1
int b = 2;               B2, B3
int a = 3;               B3
int b = 4;               B4

I'm sorry if this is a simple question. I just want to make sure what I'm doing is correct.

Thanks.

$\endgroup$
  • 1
    $\begingroup$ Your question is about scopes and it is not restricted to C or C++, but it may be good idea to ask C++ questions at Stack Overflow, it may be flagged off-topic here (I do hestitate as this one is mildly on-topic here). $\endgroup$ – Evil Apr 4 at 23:05
  • $\begingroup$ Usually language-specific questions, like other programming questions, are off-topic here. Instead, questions about programming languages in general (theory, design and implementation of PLs) are in scope. This is about scoping, which is general enough to be on-topic here, since it's not really specific to C++. For future questions that are only meaningful in C++, please follow Evil's suggestion and use StackOverflow. $\endgroup$ – chi Apr 5 at 13:40
3
$\begingroup$

Your first answer is good (assuming the scope to assign is in order as declarations go).
Each declaration is in the scope, where it is declared. In inner scope (say B2) variable $b$ is declared shadowing previous declaration. Now you cannot use outer scope variable (read, write) as is by name without scope resolution operator.

Your second table suggests that variables are available in given scopes (say B1, B2, B4), and you have taken into account shadowing, so it still looks good, but technically it is accessible and not shadowed in that scope, not declared in that scope.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.