I know and understand that global variables and magic numbers are things to avoid when programming, particularly as the amount of code in your project grows. I however can’t think of a good way to go about avoiding both.
Say I have a pre-determined variable representing the screen width, and the value is needed in multiple files. I could do…
doSomethingWithValue(1920);
But that’s a magic number. But to avoid that, I’d do…
const int SCREEN_WIDTH = 1920;
//In a later file...
extern const int SCREEN_WIDTH;
doSomethingWithValue(SCREEN_WIDTH);
And now I’m using a global variable. What’s the solution here?
In your second example,
SCREEN_WIDTHisn’t really a variable1, it’s a named constant. There is nothing wrong with using a named constant at all.In C, you might want to use an enum if it’s an integer constant because a const object isn’t a constant. In C++, the use of a const object like you have in the original question is preferred, because in C++ a const object is a constant.
1. Technically, yes, it’s a “variable,” but that name isn’t really “correct” since it never changes.