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:
Disadvantages:
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
Answers to questions are automatically generated and may not have been reviewed.
Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.