CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

The static keyword

The static keyword in C11 plays two very distinct roles:

  • When appearing before a global variable or (global) function definition, static signifies that the variable or function is only visible from within that file. If a C11 program is written in multiple source-code files, code within the 'other' files cannot 'see' the static variable or function. This enables global variables and functions to be hidden from 'other' files, and their names to re-used by 'other' files.

  • When appearing before a local variable within a function, static signifies that the variable retains its value between calls to the function. A typical use is to count the number of times a function has been called (provided that the variable has been initialised!)
    
    #include <stdio.h>
    #include <stdlib.h>
    
    //  myfunction IS ONLY VISIBLE WITHIN THIS FILE, AND IS CALLED BY main
    static void myfunction(void)
    {
        static int count = 1;    //  retains its value between function calls
        int        local = 0;    //  is re-initialised on each function call
    
        printf("count=%i  local=%i\n", count, local);
        ++count;
        ++local;
    }
    
    //  main IS NOT DECLARED AS static BECAUSE THE OPERATING SYSTEM MUST BE ABLE TO CALL IT
    int main(int argc, char *argv[])
    {
        for(int i=0 ; i < 5 ; ++i) {
            myfunction();
        }
        exit(EXIT_SUCCESS);
    }
    

    When compiled and executed will produce:
    count=1  local=0
    count=2  local=0
    count=3  local=0
    count=4  local=0
    count=5  local=0
    

C has long been criticised for using the static keyword for two distinct roles - maybe the addition of 'private' would have helped??

[The static keyword is also used in Java and C++, but has even more complicated meanings in those languages]

 


CITS2002 Systems Programming, Lecture 4, p10, 31st July 2024.