2

I was looking for a function to do some audio effect, and I found one written in C.

Inside this function, some variables are declared as Static. I am confused, I thought Static means these variables are not visibles to other files. But since they are declared inside inside a function, they are already not visible to other files.

What am I missing ?

  • 1
    possible duplicate of [What does "static" mean in a C program?](http://stackoverflow.com/questions/572547/what-does-static-mean-in-a-c-program) – ozbek Apr 14 '14 at 01:33
  • Thanks for the answers. Wouldn't declaring the static variables as globale variable be better for code lisibility ? – user3514491 Apr 14 '14 at 01:45
  • Using static also means the memory it uses is different from auto variables, so It can hold its value until the end of the program.You can see here http://en.wikipedia.org/wiki/Static_variable – Fanl Apr 14 '14 at 01:45
  • Besides holding the value until the function is called once more, as stated by merlin2011, it will improve the speed of execution if you use static in a function signature. – neowinston Apr 14 '14 at 02:33
  • if the variable is only used in that function, what's the purpose of declaring it globally? It'll make things worse when there are other similar names – phuclv Apr 14 '14 at 03:11
  • refer to this question http://stackoverflow.com/questions/13415321/difference-between-static-auto-global-and-local-variable-in-the-context-of-c-a – Abeer Apr 14 '14 at 08:39

1 Answers1

2

static inside a function means that it will hold its value the next time the function is called.

For example,

int foo() {
    static int i = 0;
    printf("%d\n", i);
    i++;
}

int main() {
    foo(); // Prints 0
    foo(); // Prints 1
}
ajay
  • 9,402
  • 8
  • 44
  • 71
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • Also, the initialization only happens the first time the function is called. – M.M Apr 14 '14 at 03:37
  • 1
    @Matt McNabb Even a bit earlier as "... All objects with static storage duration shall be initialized (set to their initial values) before program startup. ..." C11 5.1.2 1.. Although I am not certain how one could tell the difference between "program startup" and "first time the function is called" for such `static` objects inside a function. – chux - Reinstate Monica Apr 14 '14 at 04:38
  • Thanks. I was mixing up with C++ where it is not initialized until first entry. In C, the initializer must be a constant so this issue doesn't come up, as you say. – M.M Apr 14 '14 at 04:39
  • Declaring an automatic variable as static also causes its storage to be allocated off stack (autos are normally on the stack). This is useful in embedded systems which typically have a small stack. – ntremble Apr 14 '14 at 06:41