While writing in C, I have always wondered about when is the best time to use an external variable. I generally prefer to pass a pointer into a method. Is there a correct time to use an external variable and a correct time to use pointers?
3
Variables should always have the smallest scope possible. This may lead to the “annoyance” of not being able to access the variables easily, but that is actually the point! The more you hide a variable from intrusion the better. If you can keep a variable safe from all reading and writing except from one point, that is the best! This aids in writing bug-free code.
So to answer your question more specifically, pass variables as follows with #1 being the best method:
- By value
- As a pointer to variables where the address and data are constant
- As a pointer to variables where the address and data are not constant
- Globally to one file only
- Globally to all files
Right now I can’t see a reason why you should use a global variable instead of passing another parameter around except in the case where you’re dealing with performance-critical code and you might have constraints like stack memory, ABI restrictions and such.
This applies to the C code you asked in the question, wouldn’t totally fit in an object oriented context (although people also use C++ objects in performance-intensive contexts).