[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
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.

  1. include <iostream>
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; } }


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.

  1. include <iostream>
  2. include <cassert>
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' }


Keep scopes small [1]. Don't use the same name in both a scope and an enclosing scope [2].

Topic links

Reference





last edited (November 16, 2006) by bilderbikkel, Number of views: 3426, Current Rev: 7 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.