Easy Tutorial
❮ Cpp Examples Even Odd Cpp Examples Cout Helloworld ❯

C++ Variable Scope

Scope refers to the region of the program where a variable can be defined. Generally, there are three places where variables can be declared:

We will learn about functions and parameters in subsequent chapters. For now, we will discuss local and global variables.

Local Variables

Variables declared inside a function or a code block are called local variables. They can only be used by statements inside the function or the code block. The following example uses local variables:

Example

#include <iostream>
using namespace std;

int main ()
{
  // Local variable declaration
  int a, b;
  int c;

  // Actual initialization
  a = 10;
  b = 20;
  c = a + b;

  cout << c;

  return 0;
}

Global Variables

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

Global variables can be accessed by any function. Once declared, they are available throughout the program. The following example uses global 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, local and global variables can have the same name, but within a function, the value of the local variable will override the global variable. Here is 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;
}

When the above code is compiled and executed, it produces the following result:

10

Initializing Local and Global Variables

When a local variable is defined, the system does not initialize it, and you must initialize it yourself. When a global variable is defined, the system automatically initializes it to the following values:

Data Type Initial Default Value
int 0
char '\0'
float 0
double 0
pointer NULL

Properly initializing variables is a good programming practice, as failure to do so may sometimes lead to unexpected results.

❮ Cpp Examples Even Odd Cpp Examples Cout Helloworld ❯