Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
C++ Global Variables
Next article icon

C++ Global Variables

Last Updated : 16 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisites: Scope of Variables, Data Types, and Functions in C++

In C++ programming languages, a variable is a name provided to memory to store different data types. Variable values can change anytime while running the program and each variable has its own scope (or region) where it is valid to access the variable using the name given to him.

In programming, variables are not all equal. Their scope, lifespan, and accessibility in the program depend on where and how they are declared. There are two types of variables based on their scope.

  1. Local variable - The scope of these variables exists only within the block in which the variable is declared. i.e. we can access this variable only within that block.
  2. Global variable - Global variables are a special type with the widest scope possible. It is declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.

Global Variable in C++

Global variables are the variables that are declared outside of any function or class and can be accessed by any part of the program. They are generally declared at the beginning of the source file after the header file. They are available throughout the lifetime of a program and accessible from anywhere within the program.

Declaration of a Global Variable in C++

To create a global variable, we simply declare it at the top of the source file, after the header files, and before the main function. In C++, all the variables must be declared before use.

Example 1

C++
// C++ Program to illustrate Global Variable // header files #include <iostream> using namespace std;  // global variable int x = 10; // x is a global variable initialized to 10  // main function int main() {     cout << x;     return 0; } 

Output
10

Explanation

  • In this example, `x` is a global variable that can store an integer value.
  • It is initialized to 10 when the program starts.
  • Since it is declared outside any function or class, it can be accessed and modified by any function or class in the program.

Now, someone might wonder why you would want to use global variables in your program.

Example 2

C++
// C++ program to illustrate // usage of global variables #include <iostream> using namespace std;  // global variable int global = 5;  // global variable accessed from // within a function void display() { cout << global << endl; }  // main function int main() {     display();      // changing value of global     // variable from main function     global = 10;     display(); } 

Output
5  10

Explanation

  • In this example 'int global' is a Global Variable that stores an integer value.
  • It initialized with 5 when the program started.
  • After that call goes to the main function and then it calls the display function which prints the global variable.
  • After printing 5, the value of the global variable is changed to 10. Now again the display function is called and the new value of the variable global 10 is printed.

Benefits of Using Global Variables

Following are some main benefits that global variables provide:

  • Global Variable can be accessed directly by all the functions without passing an argument in the program.
  • Global Variables are very useful when many functions access the same variable.
  • Global Variable required only a one-time declaration in the program.

Drawbacks of Using Global Variables

Global variables also come with some drawbacks. Some of them are:

  • Sometimes Global Variable can cause conflict issues as multiple programs try to modify them at the same time, generally in multithreading programs.
  • It can sometimes lead to variable shadowing.
  • Global Variables can make code less readable and less maintainable.
  • Also, there is some security and bugs concern as they can be modified or accessed by any part of the program.
  • Sometimes if you use a larger number in the global variable there is a high chance of error in the program.

Conclusion

Global variables are very useful but 'difficult to track' variables in C++ programming language. They are useful because we can access the same variable in any part of the program but it must be used such that it doesn't make code less readable and less maintainable, and also takes care of security aspects. Therefore, it is suggested to use global variables rarely and carefully and prefer local variables or other alternatives whenever possible.


Next Article
C++ Global Variables

T

the_ravisingh
Improve
Article Tags :
  • C++
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • CPP

Similar Reads

    Local and Global Variables
    Local variables are declared within a specific block of code, such as a function or method, and have limited scope and lifetime, existing only within that block. Global variables, on the other hand, are declared outside of any function and can be accessed from any part of the program, persisting thr
    6 min read
    C++ Variables
    In C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
    4 min read
    Global Variables in MATLAB
    Variables in programming are generally storage spaces to store a certain type of data. There are many types of variables, but two commonly used types are local and Global variables. Generally, each MATLAB function has its own local variables. But sometimes for the sake of programming, we need to cha
    4 min read
    Can Global Variables be dangerous ?
    In a small code, we can track values of global variables. But if the code size grows, they make code less understandable (hence less maintainable). It becomes difficult to track which function modified the value and how. C++ // A C++ program to demonstrate that a // global variables make long code l
    2 min read
    Variables in Objective-C
    A variable is a place for data storage that our programs can access or manipulate. In Objective-C, variables have a defined type that specifies their shape and layout. They also cover the gamut of values and operations that we are capable of performing. Before moving further, we understand the guide
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences