WEB DEVELOPER SITE
PYTHONPHP7JAVA
 

Variable Scope in C++


A scope is a region of a program. There are generally three places where variables can be defined:

  • A variable declared inside a function or a block of code, called a local variable.

  • A variable declared in the definition of a function parameter is called a formal parameter.

  • A variable declared outside of all functions, called a global variable.

We will learn what functions and parameters are in the following chapters. In this chapter we first explain what local variables and global variables are.

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

Variables defined outside of all functions (usually at the head of the program) are called global variables. The value of a global variable is valid throughout the life of the program.

Global variables can be accessed by any function. That is, once declared, global variables are available throughout the program. The following examples use global variables and local variables:

example

#include <iostream> using namespace std; // Global variable declaration int g; int main () { // Local variable declaration int a, b; // Actual initialization a = 10; b = 20; g = a + b; cout << g; return 0; }

In a program, the names of local variables and global variables can be the same, but within a function, the value of a local variable overrides the value of a global variable. Here's an example:

example

#include <iostream> using namespace std; // Global variable declaration int g = 20; int main () { // Local variable declaration int g = 10; cout << g; 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.