WEB DEVELOPER SITE
PYTHONPHP7JAVA
 

Variable Scope in C++


All the variables have their area of functioning, and out of that boundary they don't hold their value, this boundary is called scope of the variable.


Local Variables

Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code.

Local variables are the variables which exist only between the curly braces, in which its declared. Outside that they are unavailable and leads to compile time error.

Example

There are following example of Local Variable

#include <iostream>
using namespace std;
 
int main () {
   // Local variable declaration:
   int a, b;
   int c;
 
   // actual initialization
   a = 45;
   b = 30;
   c = a + b;
 
   cout << c;
 
   return 0;
}

Run example »

Global Variables

Global variables are those, which ar once declared and can be used throughout the lifetime of the program by any class or any function. They must be declared outside the main() function. If only declared, they can be assigned different values at different time in program lifetime. But even if they are declared and initialized at the same time outside the main() function, then also they can be assigned any value at any point in the program.

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program.

Example

There are following example of Global Variable:

#include <iostream>
using namespace std;
 
// Global variable declaration:
int c;
 
int main () {
   // Local variable declaration:
   int a, b;
 
   // actual initialization
   a = 25;
   b = 30;
   c = a + b;
  
   cout <> c;
 
   return 0;
}

Run example »

Initializing Local and Global Variables

When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows −

Data Type Initializer
int 0
char '\0'
float 0
double 0
pointer NULL

It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result.