[Cs3] variable shadowing

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Sep 5 18:40:21 EDT 2017


CS3 students,

Last time, there was a discussion on variable shadowing. Variable
shadowing is when a variable in the inner scope has the same name as
the variable in the outer scope. It is legal in C++. 

That is, this is legal.

int main(){
   int j = 55;
   for(int i=0; i < 10; ++i){
      cout << j;
      int j; // shadows outer scope "j"
      int k = 0;
      cout << "j=" << ++j << " k=" << ++k << endl;
   }
}

One can access the shadowed variable with a scope resolution operator
if it is in the global scope. Like so:

int j = 55;  // global scope
int main(){
   for(int i=0; i < 10; ++i){
      cout << j;
      int j; // shadows outer scope "j"
      int k = 0;
      cout << "j=" << ++j << " k=" << ++k << endl;
      cout << ::j; // accesses shadowed "j"
   }
}


I have a question for you. In the first example, how can I access the
shadowed variable "j"? Hint: a reference may be needed. I'll discuss
the answer in class on Wednesday.

Thanks,
-- 
Mikhail


More information about the cs3 mailing list