Global Variables

Anonymous contributor's avatar
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 variable
int num = 9;
int main()
{
// Modify the value of the global variable
++num;
// Print the result
cout << num << endl;
return 0;
}

The above code produces the following output:

10

Codebyte Example

The following codebyte example demonstrates the usage of global variables:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy