Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Global Variables

User image

Published by

sanya sanya

Published at: 27th Jul, 2023
1.35 mins read

What is it?

A global variable is a variable that is accessible throughout the entire program, from any function or class. It is defined outside of any function or class and can be accessed by multiple functions or classes.

How to create?

To create a global variable, you declare it outside any function or class, typically at the top of the file or in a header file.

// Global variable declaration

int globalVariable = 10;

int main() {

// Rest of the code

return 0;

}

In the example above, ‘globalVariable’ is a global variable that can be accessed from anywhere in the program.

What is scope resolution operator?

The scope resolution operator (‘::’) in C++ is used to access global variables or functions from within a block or a local scope. It allows you to specify the scope explicitly and avoid naming conflicts between local and global variables.

Example:

#include

using namespace std;

int globalVariable = 10; // Global variable

int main() {

int globalVariable = 5; // Local variable with the same name as globalVariable

// Accessing the globalVariable using the scope resolution operator

cout << "Local variable: " << globalVariable << endl;

cout << "Global variable: " << ::globalVariable << endl;

return 0;

}

In the example above, ‘::globalVariable’ refers to the global variable, while ‘globalVariable’ refers to the local variable.

When to use?

- Storing configuration settings that need to be accessed by multiple functions or classes.

- Sharing data between different parts of the program.

- In some cases, improving performance by avoiding unnecessary parameter passing.

Library

WEB DEVELOPMENT

FAANG QUESTIONS