Variable Scope
A scope is a region of a program, and there are generally three places where you can declare a variable:
- 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, called a formal parameter.
- A variable declared outside of all functions, called a global variable.
Local variables
A variable declared inside a function or a block of code, called a local variable. They can only be used by statements inside a function or within a block of code. The following instance uses a local variable:
#include <iostream>Using NamespaceStd; IntMain(){ Local variable declaration IntA, b; int c; //actual initialization of a = ten; b = n; c = a + b;
cout
<< c; return 0;}
Global variables
Variables defined outside of all functions (usually in the head of the program), are called global variables. The value of the global variable is valid throughout the lifetime of the program.
Global variables can be accessed by any function. That is, once a global variable is declared, it is available throughout the program. The following example uses global variables and local variables:
#include <iostream>Using NamespaceStd; global variable DeclarationIntG; IntMain(){ //local variable declaration int A, B;//actual initialization a = 10 b = 20; G = a + B;<< G;return 0; /span>
Local variables and global variables can have the same name in a program, but within a function, the value of the local variable overrides the value of the global variable. Here is an example:
#include <iostream>Using NamespaceStd //global variable Declaration int g = 20; int main () { //local variable declaration int g = 10; cout << G;return 0; /span>
When the above code is compiled and executed, it produces the following results:
10
These are the differences and definitions of global variables and local variables.
C + + (variable scope)