Skip to content

Global Variables

Variables and constants can be declared outside of functions and procedures, within the program itself. Variables declared in this way are called global variables, which should be avoided. Global constants, on the other hand, are a great way of sharing consistent and meaningful values across your program.

Annotated code illustrating global values

Example

#include <string>
using std::string;
// Declare a global constant
const int INCREMENT_AMOUNT = 10;
// Declare (unnecessary) global variables
int x;
string message_text = "Hello world";
void my_procedure()
{
// you can access x, message_text, and INCREMENT_AMOUNT here
}
int main()
{
// you can access x, message_text, and INCREMENT_AMOUNT here
return 0;
}