for example in a game a currency system would need to be modifyable across the whole game on every file |
That is false.
Global variables should be avoided, since they greatly restrict how the program can operate and they spread control over an excessively large area making bugs difficult to find.
If you write a function that uses a global variable... then that function can work with that one variable
only. A better way to write the function would be to pass the variable as a parameter, then the function can work with ANY variable. This makes your code much more flexible.
Here's a simple example:
1 2 3 4
|
void damageplayer(int damage)
{
playerlife -= damage;
}
|
This code harms the player, and seems simple enough. The problem is it is restrictive. What if you decide to add multiple players? Do you make another function?
1 2 3 4 5 6 7 8 9
|
void damageplayer1(int damage)
{
player1life -= damage;
}
void damageplayer2(int damage)
{
player2life -= damage;
}
|
What if there are 3 players? 4? What if there can be dozens? Do you keep adding new functions and changing each of them?
The better solution would be to pass the player/unit in question to the function:
1 2 3 4
|
int damageplayer(int playerlife, int damage)
{
return playerlife - damage;
}
|
Now this one function can damage
any player. It doesn't matter if you have one or a million. This function will work with all of them.