C++ Global Variable with Examples

Global variables are described at the top of a program, outside of all functions. The value of a global variable remains constant throughout the execution of the program. Every function that is declared in the program, can access the global variable.

Output:

If a global variable is not initialized, then the default value is zero.

The output of the above program will be 0.

Using Scope Resolution (::)

If the name for the local variable and the global variable is the same, and we wish to access the global variable, then we make use of a scope resolution operator along with the name of the variable.

Syntax:

Program:

Output:

​Advantages of Global Variables

When multiple functions need to access the same data, a global variable comes to the rescue. A global variable can be accessed from any function in a program. Outside of the functions, you only need to declare the global variable once. If we need to access the same data in multiple functions, then we can use a global variable instead of declaring the same data multiple times inside the functions. It’s perfect for storing “constants” because it helps to maintain continuity.

​Disadvantages of Global Variables

Any function can change the value of a global variable. Now, if we access its value without using the scope resolution operator, the changed value will be returned as output. So, to prevent any changes in its value, it becomes a necessity to use the scope resolution operator.

​Global Variable in C++ Vs Java

In C++, it is not necessary to use a class to write programs. But, in Java, all the functions and data members are declared inside a class. In C++, we declare global variables at the top of the program but, in Java, we cannot do the same because every declaration has to be done inside the class and if we declare it outside the class, then it would not be accessible by the object of that class.

So, in Java, to declare a global variable inside a class, we use the keyword static along with the name of the variable.

Program for global variable declaration in Java:

Output:

In this program, we created a class named staticVariable and inside the class, we created a function named display. Inside the class, we created a static variable with a value of 20. In the main function, we created an object named obj1 of class staticVariable to access all the variables and functions of this class with the help of the object. Now we call the display function inside the main function using object obj1 to display the output of the program (here, the value of static member ‘a’).

Leave a Comment

Your email address will not be published. Required fields are marked *