C Appropriate Use of Global Vars
An answer to this question on Stack Overflow.
Question
I'm building a minishell in C, and have come to a roadblock that seems that it could be easily fixable by using global variables(3 to be exact). The reason I think globals are necessary, is that the alternative would be to pass these variables to almost every single function in my program.
The variables are mainargc, mainargv, and shiftedMArgV. The first two are the number of arguments, and argument list passed to main, respectively. The variable shiftedMArgV is the argument list, however it may have been shifted. I'm trying to create builtin functions shift and unshift, and would make shiftedMArgV point to different arguments.
So, would it be stupid to just make these global? Otherwise I will have to revise a very large amount of code, and I'm not sure I'd be losing anything by making them global.
If I do make them global, would doing so from the main header file be foolish?
Thanks for the help guys, if you need any clarification just ask.
Answer
I would say that it is not stupid, but that you should proceed with a certain caution.
The reason globals are usually avoided is not that they should never be used, but rather that their usage has led people to frequently led programmers to crash and burn. Through experience one learns the difference between when it is the right time and when it is the wrong time.
If you have thought deeply about the problem you are trying to solve and considered the code you've wrote to solve this problem and also considered the future of this code (i.e. are you compromising maintainability) and feel that a global is either unavoidable or better represents the coded solution, then you should go with the global.
Later, you may crash and burn, but that experience will help you later discern what a better choice may have been. Conversely, if you feel as though not using the globals may lead to crashage and burnage, than this is your prior experience saying you should use them. You should trust such instincts.
Dijkstra has a paper in which he discusses the harm the goto statement may cause, but his discussion also, in my opinion, explains some of our difficulties with globals. It may be worth a read.
This answer and this answer may also be of use.