[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppScope
In C++, a scope is defined by accolades.
A variable 'without scope' is called a global variable. When the compiler needs to choose between a global and local variable, it will choose the local.
Keep scopes small [1]. Don't use the same name in both a scope and an enclosing scope [2].
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppScope
(C++) Scope
The scope of a variable is the area where its name is valid. A variable declared inside a function is only valid inside that function. Thus its scope is inside the function (from Doctor Slush, Scope).In C++, a scope is defined by accolades.
int main() { int a = 0; { int b = 0; } //b goes out of scope for (int i=0; i<10; ++i) std::cout << "Hello world" << std::endl; } }
- include <iostream>
A variable 'without scope' is called a global variable. When the compiler needs to choose between a global and local variable, it will choose the local.
int a = 10; //Global 'a' int main() { int a = 0; //Local 'a' assert(a==0); assert(::a==10); //Use scope operator to get global 'a' }
- include <iostream>
- include <cassert>
Keep scopes small [1]. Don't use the same name in both a scope and an enclosing scope [2].
Topic links
- #include
- scope operator'::'
- stream out operator '<<'
- assert
- cout
- endl
- for
- #include
- int
- iostream
- main
- return
- scope operator'::'
- std
- stream out operator '<<'
Reference
- 1) Bjarne Stroustrup. The C++ Programming Language (3rd edition).ISBN: 0-201-88954-4. item 4.10.1: 'Keep scopes small'.
- 2) Bjarne Stroustrup. The C++ Programming Language (3rd edition).ISBN: 0-201-88954-4. item 4.10.2: 'Don't use the same name in both a scope and an enclosing scope'.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
