Introduction to Functions

Pros and Cons of Global Variables in C++

What are the advantages and disadvantages of using global variables in C++?

Abstract art representing computer programming

Global variables are variables that are defined outside of any function and can be accessed from anywhere in the program. They have both advantages and disadvantages.

Advantages:

  1. They can be accessed from anywhere in the program, which can be convenient.
  2. They can be used to share data between functions without having to pass the data as arguments.

Disadvantages:

  1. They can make code harder to understand and maintain, because it's not clear which functions are modifying the global state.
  2. They introduce the potential for naming collisions. If two parts of the program use the same global variable name, it can lead to bugs.
  3. They make code less modular and harder to reuse, because functions that use global variables are tied to the global state.

In general, it's considered good practice to minimize the use of global variables. When you do use them, make sure to give them clear, descriptive names and document their purpose and usage.

Here's an example of a global variable:

#include <iostream>

int globalCounter = 0;

void incrementCounter() { ++globalCounter; }

int main() {
  incrementCounter();
  incrementCounter();

  // Outputs 2
  std::cout << globalCounter;
}
2
This Question is from the Lesson:

Introduction to Functions

Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Introduction to Functions

Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved