Home » C++ programming language

Global Variable in C++ with Example

C++ Global Variables: In this article, we will learn what are the Global variables in C++, how to declare, assign and access a global variable?
Submitted by Manu Jemini, on September 28, 2017

Variable Scope in C++ Inside a function or a block which is called local variables, The variables which are declared outside of all the function and accessible from all functions including main function are known as Global variables.

Consider the program: In this Example, we have shown how global and local variable behave and to manipulate them.

#include <iostream>
using namespace std;

// defining the global variable
int a=10;

int main()
{
    //local variable
    int a=15;
    cout<<"local a: "<<a<<" Global a: "<<::a;
    
    // Re-defining global variable by using ::
    ::a=20;
    cout<<"\nlocal a: "<<a<<" Global a: "<<::a;
    return 0;
}

Output

local a: 15 Global a: 10
local a: 15 Global a: 20





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.