You may have been told to avoid global variables. This is good advice in many cases, but there are times when global variables are necessary and useful.
Many programming languages allow for both global and local variables:
Global variables can be easier because they can be accessed from anywhere - this means you don't have to think about each of your variables and decide where it should be defined, and how to make it accessible within each function that needs to use it.
The problem is that, because it can be accessed from anywhere, there is nothing to stop a function from changing a variable that it shouldn't really need to change, causing an unexpected side effect. This can create bugs that are very difficult to track down.
When you only use local variables, you are forced to think more about the design of yours software, which might take a little longer but makes your software better and more reliable in the end.
Global constants are a special case. Since they are constant, they can't be accidentally altered and cause unexpected side effects.
Global constants are a good thing and you should use them! See more in the section on [variables and assignment](\gcse\programming-techniques\variables-and-expressions\variables-and-assignment).
While there is always a risk in using global variables, it is sometimes a risk worth taking.
For example, suppose you are writing a game. You might have a game object that stores all the important game information - the score, player lives, what level you are on, etc. This game object might be used in many places in your code, you might decide that it is a lot easier to store the game object in a global variable. This might be justified because:
There is quite a low risk of introducing bugs by using a global game object, so you might consider this as a way to simplify the code, especially for a simple game like space invaders.
Copyright (c) Axlesoft Ltd 2021