How to Declare a Global Variable in C++?

In C++, global variables are like normal variables but are declared outside of all functions and are accessible by all parts of the function. In this article, we will learn how to declare a global variable in C++.

Global Variable in C++

We can declare a global variable, by defining it outside of all functions at the top after the header files. Once the global variable is declared, it can be accessed from the scope of the main function as well as any inner construct (loop or if statement) inside it.

Syntax to Declare Global Variable in C++

A global variable is declared in the same way as any other variable but it is placed outside of every function.

dataType globalVariableName = variableValue;

C++ Program to Declare Global Variables 

The below example demonstrates how we can declare global variables in C++.

C++
// C++ program to declare a global variable

#include <iostream>
using namespace std;

int g_value = 10; // declaring the global variable

void display()
{
    cout << "Global variable value: " << g_value << endl;
}

int main()
{
    display(); // can access the global variable from a
               // function
    cout
        << "Global variable value: " << g_value
        << endl; // can access the global variable from main

    return 0;
}

Output
Global variable value: 10
Global variable value: 10

Note: Avoid the excessive use of global variables because it makes a program hard to understand and debug.


Contact Us