C++ Beginner : How to Using Local, Global Variables In C++

C++ for beginners : How to Using Local Variables inside a functions or block and Global Variables outside of all the functions In C++? As we know, the c++ programming language also have variables was defined in a of functions or a block or outside of the functions.

Read : C vs C++ programming Languages
If Statements in C++

Today we will learn C++ programming languages just for beginner, where we learn how to using local variables and global variables in a functions or block.

How to Using Local, Global Variables In C++

Local Variables

Local variables can be declared inside a function or block. A local variables only can used inside of a functions or a block, the statements that are outside the function cannot use this local variables. Here is the example using local variables :
#include 
using namespace std;

int main (){
// Declaration Local variable
int x, y;
int z;

// initialization block
x = 5;
y = 15;
z = x + y;

cout << z;

return 0;
}

Global Variables

Global variables is declared outside of a block or a functions, the global variables are usually declared in the top line of a program. Not just for programming language C++, but almost the entire programming language has same with the C++ language.

The virtue of global variables is accessible to of anything functions in the programs. because a global variable is created to be accessible from the existing all in a program. Here is the example using Global variables :
#include 
using namespace std;

// Declaration Global variable
int x;

int main ()
{
// Declaration Local variable
int y, z;

// initialization block
y = 25;
z = 55;
x = y + z;

cout << x;

return 0;
}

A Program may have the same variable name for local and global variables, but the value used is the value of a local variable. As an example:
#include 
using namespace std;

// Declaration Global variable
int x = 100;

int main ()
{
// Declaration Local variable
int x = 25;

cout << x;

return 0;
}

When the program is running will result "25"