Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

static in C

Name: Anonymous 2010-10-16 17:23

I can see why you would want static variables in functions but what's the point of static globals?

Name: Anonymous 2010-10-16 17:54

>>1

All variables with the "static" storage class qualifier are global, i.e., there exists only one copy of the variable.  Static variables declared at file scope are only accessible from that translation unit, those declared at function scope are only accessible from that function.  Static variables (and functions) have no linkage.

The "no linkage" part is the most important part.  Suppose you have static int myglobal; defined in header "defs.h", and files "main.c" and "input.c" both include "defs.h".  Then they both get their own separate copy of myglobal, because it has no linkage they are not combined into one object.

If an object has no linkage, you can name it whatever you want without worrying about it clashing with another object defined somewhere else in the program.  Basically, you use it any time you have a global variable that you want to be accessible from only a few functions, as long as they're all defined in the same translation unit.

It's much more common to see static functions.  I use them quite often, they're kind of like private functions in C++ except they're much nicer because they don't go in the header files.

(P.S. Yes, there is a such thing as an "object" in C.)

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List