Originally Posted by jvolkman
This is true, but part of becoming a successful developer (or any professional really) is picking up the good habits and avoiding the bad. I say generally frowned upon because there are definitely cases where the use of globals is desirable or even necessary. However, a novice developer that builds a habit of using globals because they make something easier, such as this case, is likely to run into problems down the line.
This Stack Overflow article has some pretty good discussion: http://programmers.stackexchange.com/a/148109
First of all this doesn't really require what I would call a true global... it would be limited to that one file in scope. It would just have to be declared so that the specific function could access it, within that file (ie just stick it outside of main, iirc). It's effectively no different from passing it in as a parameter every time (though now the function is not independent of the surrounding code).
Second of all, in one reply to what you linked, this is a counterargument, which specifically addresses the case we're talking about:
None of that explains why readonly global variables are bad … which the OP explicitly asked about. It’s an otherwise good answer, I’m just surprised that the OP marked it as “accepted” when he explicitly addressed a different point.
You'd declare it, set it, and then it would not be changed... many of the specific problems that were marked by that person are totally irrelevant to this use case.
Originally Posted by DuckieHo
If you're using globals, it indicates that your objects are not independent....
Globals only when necessary is a good habit.
There are stuff that are definitely frown upon because they may technically work... there are better ways and for good reason. It might be readability, performance, flexibility, correctness, etc.
I read a similar debate on stackoverflow regarding using jump in PHP. I think the main point of contention was readability. Performance? That utterly depends on how well you use things. Correctness? If it works, it's correct. Flexibility? Depends on a lot of factors.
Independence of the function is probably the most valid argument. Depends on what you intend to reuse: the function, or the whole file.
For this though if you needed to keep the prototype the same I think it'd be your only option.
I suppose you can have the function declare a static int if you so desire to keep the function independent. Set it once, to max, do not touch it afterwards. You'd probably need to make another static int that keeps track of how many times you've executed, and then reset both variables when one equals the other.
This is kind of starting to get off the rails though isn't it?Edited by stolemyowncar - 10/23/13 at 9:04am