ultrainstinct
ultrainstinct

Reputation: 255

Static variables clarification

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?

Upvotes: 0

Views: 67

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754900

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.

Upvotes: 1

Variable Length Coder
Variable Length Coder

Reputation: 8116

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.

Upvotes: 4

Related Questions