xxxxxxxxxx
// a.cpp
int x = 5;
// b.cpp
extern int x; // allows b.cpp to access 'x' from a.cpp
xxxxxxxxxx
#include<iostream>
using namespace std;
// Global variable
int a = 3;
int main()
{
// Local variable
int a = 7;
cout << "Value of global variable a is " << ::a<<endl;
cout<< "Value of local variable a is " << a;
return 0;
}
Try it yourself
xxxxxxxxxx
#include <iostream>
// Global Variable
int globalVariable = 10;
void someFunction() {
// Accessing globalVariable
std::cout << "Value of globalVariable: " << globalVariable << std::endl;
}
int main() {
// Modifying globalVariable
globalVariable = 20;
// Calling someFunction
someFunction();
return 0;
}
xxxxxxxxxx
#include<bits/stdc++.h>
using namespace std;
//Declaring a global variable
int a = 5;
int main()
{
//Printing the value of a
cout<<"The value of a is "<<a<<"\n";
//Modifying the value of a
a--;
//Printing the value of a
cout<<"The value of a is "<<a<<"\n";
return 0;
}
xxxxxxxxxx
The value of a is 5
The value of a is 4