Declaration of a Global Variable in C++
To create a global variable, we simply declare it at the top of the source file, after the header files, and before the main function. In C++, all the variables must be declared before use.
Example 1
C++
// C++ Program to illustrate Global Variable // header files #include <iostream> using namespace std; // global variable int x = 10; // x is a global variable initialized to 10 // main function int main() { cout << x; return 0; } |
10
Explanation
- In this example, `x` is a global variable that can store an integer value.
- It is initialized to 10 when the program starts.
- Since it is declared outside any function or class, it can be accessed and modified by any function or class in the program.
Now, someone might wonder why you would want to use global variables in your program.
Example 2
C++
// C++ program to illustrate // usage of global variables #include <iostream> using namespace std; // global variable int global = 5; // global variable accessed from // within a function void display() { cout << global << endl; } // main function int main() { display(); // changing value of global // variable from main function global = 10; display(); } |
5 10
Explanation
- In this example ‘int global’ is a Global Variable that stores an integer value.
- It initialized with 5 when the program started.
- After that call goes to the main function and then it calls the display function which prints the global variable.
- After printing 5, the value of the global variable is changed to 10. Now again the display function is called and the new value of the variable global 10 is printed.
C++ Global Variables
Prerequisites: Scope of Variables, Data Types, and Functions in C++
In C++ programming languages, a variable is a name provided to memory to store different data types. Variable values can change anytime while running the program and each variable has its own scope (or region) where it is valid to access the variable using the name given to him.
In programming, variables are not all equal. Their scope, lifespan, and accessibility in the program depend on where and how they are declared. There are two types of variables based on their scope.
- Local variable – The scope of these variables exists only within the block in which the variable is declared. i.e. we can access this variable only within that block.
- Global variable – Global variables are a special type with the widest scope possible. It is declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.
Contact Us