1

Possible Duplicates:
What does “static” mean in a C program?
Static vs global

What does "static" mean in C, giving the following example: "static struct ........"?

And what is the diffrence between this and "struct ......" without the "static"?

Community
  • 1
  • 1
nisnis84
  • 229
  • 1
  • 4
  • 7
  • 3
    What does "search engine" mean? Dupe many times, please look before you leap. http://stackoverflow.com/questions/572547/what-does-static-mean-in-a-c-program – Chris Lutz Feb 18 '10 at 08:43

3 Answers3

3

Outside a function, static makes whatever it's applied to have file scope. For example:

int a_function(int x) { ... }

This function will have global linkage, and can be accessed by any other object file. You just have to declare it to use it, as is usually done in a header file:

int a_function(int x);

However, if you use static in the definition, then the function is visible only to the source file where it is defined:

static int a_function(int x) { ... }

In that case, other object files can't access this function. The same applies to variables:

static int x;

This makes x a global variable, visible only within it's source file. A "static struct" by itself doesn't do anything, but consider this syntax:

struct {
    int x;
    int y;
} p1, p2;

This declares two global variables (p1 and p2), each of an "anonymous" struct type. If you append static:

static struct {
    int x;
    int y;
} p1, p2;

Then static applies to p1 and p2, making them visible only within their source file.

Joao da Silva
  • 7,353
  • 2
  • 28
  • 24
1

static tells that a function or data element is only known within the scope of the current compile.

In addition, if you use the static keyword with a variable that is local to a function, it allows the last value of the variable to be preserved between successive calls to that function.

So if you say:

static struct ...

in a source file no other source files could use the struct type. Not even with an extern declaration. But if you say:

struct ...

then other source files could access it via an extern declaration.

ardsrk
  • 2,407
  • 2
  • 21
  • 33
0

I'm not a C programmer, but if static in C means anything like it does in other languages I use STATIC STRUC, meaning that the structure is common amongst all instances of this class.

Say I had a class variable called Z. The usual behaviour is that the value of this variable is specific to a particular instance of a classs, but when it is static, all instances of the class share the same value of Z at all times.

I don't know how this applies to C, isn't C object-less?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dal Hundal
  • 3,234
  • 16
  • 21