Well here I am sitting down for the millionth time telling myself “I’m going to write a game using SDL and C++” except this time I told myself I was going to write it in C. This is because SDL itself is written in C and it seems to just make sense to me. The game that I’m writing will be a simple “SHMUP” (Shoot ’em up) and it will probably be very short code-wise, so I’m wondering are a couple global variables bad? (like “struct base basevar;” or “int SCREEN_W” or something)?
Share
Global variables aren’t inherently “bad”. However, they can easily lead to very bad code (in the sense of readability, testability, maintainability) if used carelessly. They can also lead to pernicious multi-threading issues (if you’re using threads), again, if used carelessly.
Some people have a blanket rule that you should never use them. IMHO, this is too draconian, and if followed religiously, can lead to people passing around a pointer to a big
everything_tto all functions, which isn’t a great deal better (although even this simple approach makes your code re-entrant). However, please don’t read this as advocation for “just go wild with globals!”. They are the right answer only in a few situations.In your example, it sounds like you have a bunch of settings/parameters that don’t really change. Consider at least grouping them into a
settingsstruct; this gives you the flexibility later to have e.g. aconst settings *getSettings()function.