Global Variables
Anonymous contributor
Published Dec 9, 2024
Contribute to Docs
In C++, global variables are variables that are defined outside of all functions and are usually defined at the beginning of a program. They can be utilized anywhere in the program after their declaration.
Syntax
data_type global_variable = value;
data_type
: Specifies the data type of the global variable.global_variable
: The name of the global variable.value
(Optional): The initial value assigned to the global variable.
Example
The following example defines a global variable, modifies its value and prints the result:
#include <iostream>using namespace std;// Define a global variableint num = 9;int main(){// Modify the value of the global variable++num;// Print the resultcout << num << endl;return 0;}
The above code produces the following output:
10
Codebyte Example
The following codebyte example demonstrates the usage of global variables:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours