Variable Scope

A scope of a variable determines the region of a program which can access it and also the lifespan of the variable i.e how long it lives. Based on the scope, variables can be categorized as local & global.

Local Variables
Variables that are declared inside a function or a block are called local variables. They can be accessed within that function only and are destroyed as soon as the function ends. Local variables have function or block scope. See the program below for more clarity.

Global Variables
Variables that are declared outside all functions (usually at the top of the program) are called global variables. They have program scope i.e they can be accessed everywhere and they die only after the program execution ends. Let’s look at simple program to differentiate between local & global variables :

 * This program illustrates local & global variables

using namespace std;

int x = 10; // global variable

// main() function
int main() {
   int x = 20; // local variable inside function
   // a simple block
      // local variable inside block
      int x = 30;
      cout << "Printing local (inside block) x = " << x << endl; // prints 30 
   cout << "Printing local x = " << x << endl; // prints 20

   // use scope resolution operator ( :: ) to access global x 
   cout << "Printing global x = " << ::x << endl; // prints 10
   return 0;

Scope Resolution Operator ( :: ) is used to access the global variable if local and global variables are declared with the same name.
Local variables are not initialized by the system. It is programmer’s responsibility.
Global variables are initialized automatically. A variable of type int, float or double is initialized to 0.
A char type variable is initialized to ‘ \0 ‘ & a pointer type variable is initialized to NULL.

About    Contact    Sitemap    Terms    Privacy