C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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








COMMENTS