Variable Scope In C++ Language

In today’s tutorial we will discuss variable scope in C++ Language. Variable scope refers to the part of the program where you can access the variable. In C++ variable scope is determined when compiling your codes and independent of function call stack. In this tutorial we will be looking at the various types of variables according to where they are accessible in the program. These variables may include;

  • Local variables- these are variables that are defined inside a function or a block.
  • Global variables- these are variables that are defined outside all the functions.
  • Formal parameters- these are variables that are defined in the definition of function parameters, as we will discuss in our later in our chapters.

In the following section we will discuss local variables and global variables in details giving out relevant examples.

1. Local Variables

As we have explained local variables are declared inside a function or block. These variables can only be utilized by the statements that are in that function or block, they can’t function outside on their own. Look at this example here;


#include 
using namespace std;
int main ()
{
// Declare local variable:
int x, y;
int z;
// actual initialization
x = 25;
y = 30;
z = x + y;
cout << z;
return 0;
}

These refers to the variables that are declared outside all the functions, especially they are declared at the top of the program. These variables can be utilized in your entire program after it's declaration by any function and they hold their values in the life-time of your program. Look at the example below;


#include 
using namespace std;
// Declare you global variable:
int z;
int main ()
{
// Declare your local variable:
int x, y;
// actual initialization
x = 25;
y = 30;
z = x + y;
cout << z;
return 0;
}

How To Initialize Variables?

In this part we will discuss how you can initialize both global and local variables. Variable initialization refers to specifying an initial value to assign to it before it is used. If you do not initialize variables well it may give unexpected results. For the local variables you must initialize them manually but global variables are automatically initialized when you define them as; int =0, char='\0', float=0, pointer=null, double=0.

Thanks for reading through our tutorial, hope you understand various types of variable scope. As we continue learning about C++ language, hoping to meet you in our next tutorial. Remember to subscribe to our youtube channel for video presentations and live sessions we hold here; YOUTUBE LINK.