Scope of Variables in C++

All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous code at the beginning of the body of the function main when we declared that a, b, and result were of type int.

A variable can be either of global or local scope:

Global Variable

A global variable is a variable declared in the main body of the source code, outside all functions.

Local Variable

While a local variable is one declared within the body of a function or a block.

Below is an image to ullustrate that, have a look at it.

VS Code Code Runner

Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration.

The scope of local variables is limited to the block enclosed in braces {} where they are declared.

Lets take an example, if they are declared at the beginning of the body of a function like in function main their scope is between its declaration point and the end of that function.

In the above example, means that if another function existed in apart from main, the local variables declared in main could not be accessed from the other function and vice versa.

Initialization of variables

When we are declaring a regular local variable, its value is by default undetermined.

But you may want a variable to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable.

We have two ways to do that in C++:

The first one, known as c-like, is done by appending an equal sign followed by the value to which the variable will be initialized:

type identifier = initial_value;

For example, if we want to declare an int variable called a as identifier and initialized with a value of 0 at the moment of declared, we could write:

int a = 0;

The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (()):

type identifier (initial_value);

Let's take an example:

int a = (0);

Let's look at the below example:

// initialization of variables
#include <iostream>
using namespace std;
int main(){
  int a = 5; // initial value = 5
  int b (2); // initial value = 2
  int result; // initial value undetermined
  a = a + 3; 
  result = a - b;
  cout<< result;

  return 0;
}

Now that you have learned where variables are living in C++ programming. Lets learn something about Strings in C++ in the next section.