ch3-Shadow (Variable shadowing or name masking)

Chapter_3     Exercise_3-7     Scope OnTheFly     Exercise_3-8







Shadow.cpp         download


// variable shadowing or name masking
#include <iostream>
using std::cout;
using std::endl;

int main()
{
int scp = 0; // scope
// outer scp visible here
cout << "Outer:" << endl;
cout << "scp = " << scp << endl; // 0
{
// outer scp still visible here
scp++; // 1
cout << "Inner:" << endl;
cout << "scp = " << scp << endl; // 1
int scp = 10; // redefine in inner scope
// inner scp visible here, outer scp no longer visible here
cout << "scp = " << scp << endl; // 10
{
// inner scp still visible here
scp++; // 11
cout << "Innermost:" << endl;
cout << "scp = " << scp << endl; // 11
int scp = 20; // redefine in innermost scope
// only innermost scp visible here
cout << "scp = " << scp << endl; // 20
} // <-- innermost scp destroyed here
// innermost scp not available here
// inner scp still visible here
cout << "Inner:" << endl;
cout << "scp = " << scp << endl; // 11
} // <-- inner scp destroyed here
// inner and innermost scp not available here
// outer scp still visible here
cout << "Outer:" << endl;
cout << "scp = " << scp << endl; // 1

return 0;
} // <-- outer scp destroyed here
/*
g++ Shadow.cpp -o Shadow
./Shadow
Outer:
scp = 0
Inner:
scp = 1
scp = 10
Innermost:
scp = 11
scp = 20
Inner:
scp = 11
Outer:
scp = 1
*/





Note:  See also ch3-Shadow on the blog Thinking_in_C#, Chapter_3, Section UnInitialized, and ch3-Shadow on the blog Thinking_in_Java, Chapter_3, Section UnInitialized.









Chapter_3     Exercise_3-7     Scope BACK_TO_TOP OnTheFly     Exercise_3-8



Comments

Popular posts from this blog

Contents