There might be another question like this on stack but I am not completely sure. So on to my question. My professor told everyone, "NEVER USE GLOBAL VARIABLES". But she said that static variables are allowed as long as you give a good enough reason. So my question is, under her criteria, is a static variable declared at the global level ok?
-
Did your instructor give you specific criteria other than "have a good reason"? And if so, what would your justification be?user1508519– user15085192014-01-25 01:56:24 +00:00Commented Jan 25, 2014 at 1:56
-
I'm guessing no (unless, as remyabel points out, you have a really good reason) -- but since it's her criteria, you need to ask her to clarify; we can't read her mind. My own opinion is that she's giving you a rule of thumb -- if there's a solution that doesn't involve globals it's usually a better one so you should go looking for it first -- but the real world sometimes doesn't give you as much choice as you'd like.keshlam– keshlam2014-01-25 01:56:49 +00:00Commented Jan 25, 2014 at 1:56
-
If she's cute enough, I could maybe wine & dine her and ask her what she means by a "good enough reason".kuroi neko– kuroi neko2014-01-25 01:59:04 +00:00Commented Jan 25, 2014 at 1:59
-
My good reason is that I have to process a 2D array in a recursive function that requires to be of return type void. So passing a 2d array as a pointer and dereferencing is kind of beyond my knowledge.ultrainstinct– ultrainstinct2014-01-25 02:02:46 +00:00Commented Jan 25, 2014 at 2:02
2 Answers
Unfortunately static has two meanings in C. When applied to a global variable, it means that the visibility of this symbol is in the file scope. When applied to a local variable, it means that this variable retains its value between calls (i.e., it's not really a local variable). Your professor is referring to the latter, not the former, when she says they are allowed.
2 Comments
There are times when global variables are useful. Consider stderr: it would be a pain to have to define it in every file you needed to use it in; it is sensibly defined as a global variable.
There are times when it is sensible to store a variable at file scope without external linkage (which you do using static as part of the definition of the variable, outside the scope of any function). For example, if you have a suite of functions which need to share some state but the API does not pass a handle back to the calling code (so there isn't an analogue of open and close — or create and destroy), then one or more static variables at file scope make sense.