135k views
0 votes
Which of the following are good examples of things that should be stored as global variables?

I - The parameter e to a callback function
II - The ball in the game the user is playing
III - A counter keeping track of how many times the user has pressed the spacebar
IV - A for loop counter
V - The color of a rectangle that is only used in one function

1 Answer

2 votes

Final answer:

Good examples of things to store as global variables include the ball in the game the user is playing and a counter for the spacebar presses. Parameters to callback functions, for loop counters, and specific function variables like the color of a rectangle, should not be global.

Step-by-step explanation:

The question asks which of the given items should be stored as global variables in a program. Global variables are variables that are declared outside of any function, making them accessible from any part of the code. However, using global variables excessively is generally considered bad practice due to potential conflicts in the code and debugging difficulties. Nonetheless, some uses are justified.

Of the options given:

  • II - The ball in the game the user is playing: This is a good candidate for a global variable as it represents a game object likely to be accessed from multiple functions within the game.
  • III - A counter keeping track of how many times the user has pressed the spacebar: This might be used across various functions, particularly if multiple aspects of the game or application respond to the spacebar presses.

The other options are better suited to local scope usage:

  • I - The parameter e to a callback function should be passed as an argument rather than stored globally.
  • IV - A for loop counter is typically local to the loop it's controlling.
  • V - The color of a rectangle that is only used in one function should remain local to that function to avoid unnecessary global state.
User Sean Burton
by
7.8k points