> For the complete documentation index, see [llms.txt](https://wiki.tylerqwong.me/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wiki.tylerqwong.me/cs/statics-volatiles-and-externs.md).

# 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

* [Understanding the "extern" keyword in C](https://www.geeksforgeeks.org/understanding-extern-keyword-in-c/)
* [Stack Overflow, "What does 'static' mean in C?"](https://stackoverflow.com/questions/572547/what-does-static-mean-in-c)
* [Stack Overflow, "Why won't extern link to a static variable?"](https://stackoverflow.com/questions/2841762/why-wont-extern-link-to-a-static-variable)
* [Wikipedia, Volatile](https://en.wikipedia.org/wiki/Volatile_\(computer_programming\))
