Statics, Volatiles, and Externs

Type Qualifiers

Static

When used to declare a variable inside of a function: allows that function to keep the value of that variable between calls. This is useful for functions that need to track a value between invocations but don't need to share that value with any other function (in which case you would simply use a global). Consider the following code snippet:

void foo(){

    int var = 10;
    static int statvar = 10;
    
    var += 5;
    statvar += 5;

    printf("var=%d statvar=%d", var, statvar);
}

Every invocation of foo will print out "var=15" and "statvar=x" where x is ten plus five times the number of times foo has been called.

When used to declare a global variable: sets the scope of that global variable to within the current file only. Syntax is very similar to non-static global variables.

Volatile

Volatile indicates that the variable in question may be changed by external processes such as an interrupt, a parallel processor, or an external device. This prevents the compiler from optimizing away sequential read values.

Extern

When used to qualify a variable: Allows you to declare a variable without defining it (in other words set the type without allocating memory for it). Also forces the variable to a global scope. When you use extern you have to remember to define it at some point or else the compiler will throw an error.

When used to qualify a function: Effectively does nothing because functions are implicitly global already.

Additional Resources

Last updated

Was this helpful?