Declare a Global Variable in C++



In C++, a global variable is a variable that is declared outside of any function or class. It can be accessible from any part of the function.

Declaration of a Global Variable

The global variables are declared after the heading file inclusions section and before starting the main() function. The declaration is simple just like a normal variable declaration. You need to use data type and variable name. You can also initialize them if required.

Syntax

The following is the basic syntax of declaring global variable:

datatype global_var_name = var_value;

Example of Global Variable Declaration

In this example, we declare global variable x to store the integer value that is declared outside the main() function and access the value within the main() function:

Open Compiler
#include<iostream> using namespace std; // global variable int x = 100; // main function int main() { cout << x; return 0; }

The above program obtained the following result:

100

As we disscussed the accessibility of global variable. So, now we will learn how to change the value of global variable by another function and print the result.

Example of Changing Value of Global Variable

Following is the illustration of program based on the above statement:

Open Compiler
#include<iostream> using namespace std; // global variable int global_var = 10; void fun1() { // modification of global variable global_var = 20; } // display function void fun2() { cout << global_var << endl; } int main() { // call the function where value modified fun1(); // call the function for displaying result fun2(); return 0; }

The above code produces the following result:

20
Updated on: 2025-06-02T14:02:21+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements