Asked in
Software and Applications (non-game)
Computer Programming

What does it mean for a variable to be global?

Answer

User Avatar
Wiki User
November 26, 2008 7:50PM

A global variable can be accessed from any area of your program. This differs from a local variable since local variables can only be accessed (and only exist) inside the function that declared them. For example:

int global_var = 0; // Declared globally

void function_x()

{

int local_var = 0; // Declared locally (inside function_x)

global_var = 1;

}

int main()

{

function_x();

// This will print "global_var = 1"

std::cout << "global_var = " << global_var << endl;

// This will cause a compiler error "local_var undeclared" since local_var only exists inside function_x

std::cout << "local_var = " local_var << endl;

return 0;

}

The reasons for doing this is so that you don't have functions modifying variables that they should not have access to.