Recommended textbooks for you
Microsoft Visual C#
Publisher:Cengage Learning,
EBK JAVA PROGRAMMING
Publisher:CENGAGE LEARNING - CONSIGNMENT
EBK JAVA PROGRAMMING
Publisher:CENGAGE LEARNING - CONSIGNMENT
Programming Logic & Design Comprehensive
C++ Programming: From Problem Analysis to Program...
Publisher:Cengage Learning
Microsoft Visual C#
ISBN:9781337102100
Author:Joyce, Farrell.
Publisher:Cengage Learning,
EBK JAVA PROGRAMMING
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
EBK JAVA PROGRAMMING
ISBN:9781305480537
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Programming Logic & Design Comprehensive
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage
C++ Programming: From Problem Analysis to Program...
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
Here let us explain what local and global variables are.
Local VariablesVariables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables:
#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 VariablesGlobal variables are defined outside of all the functions, usually on top of the program. The global variables will hold their type throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:
#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; }A program can have same name for local and global variables but value of local variable inside a function will take preference. For 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