COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button
C++ LANGUAGE GLOBAL VARIABLES
Global Variables
Global variables are defined outside of all the functions, usually on
top of the program. The global variables will hold their value 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
No comments:
Post a Comment