Tuesday, April 5, 2016

'Static' Storage Class Specifier

  • Value of a 'Static' variable will be maintained across the function invocations. If a variable is declared using 'Static' qualifier at the top of the source file, then the scope of that variable is within the entire file. Files outside the declared file can't access the declared static variable. 
  • 'Static' variables declared within a function or a block, also known as local static variables, have the scope that, they are visible only within the block or function like local variables. The values assigned by the functions into static local variables during the first call of the function will persist/available until the function is invoked again.
  • 'Static' variables are by default initialized with value 0.

Let's see the effect of declaring a local and global variable with 'Static' keyword.
  1. #include <stdio.h>
  2. static int global_static_variable = 1;
  3.  
  4. static void static_variable_test() {
  5. static int local_static_variable;
  6. printf("local_static_variable:%d\t", local_static_variable);
  7. local_static_variable++;
  8. printf("global_static_variable:%d\n", global_static_variable);
  9. global_static_variable++;
  10. }
  11. int main()
  12. {
  13. static_variable_test();
  14. static_variable_test();
  15. }
  16.  
  17. Output:
  18. local_static_variable:0 global_static_variable:1
  19. local_static_variable:1 global_static_variable:2
Few points to note here are
  1. 'Static' variable got initialized with value 0 by default. (We didn't initialize the variable 'local_static_variable' with a value, but it got initialized with 0 automatically)
  2. Value of the the local variable 'local_static_variable' is retained across invocations of function 'static_variable_test()'
'Static' and Global functions/variables
In C programming language, functions are global by default. That means, by default function declared in a file can be accessed from code with in another file. But when you apply static keyword to a functions, it makes the function accessible only from that file. So if you want to restrict access to a function from code in other files, you can declare the function as static.

In the example given above, the function 'static_variable_test' will be visible only with in the file it's declared. Also, if you declare a global variable as static, code in other files cannot access the variable. In simple words, declaring a global function or variable as static gives it internal linkage.

No comments: