C Programming Static Variables
Given a Permanent Address in Memory
When the compiler encounters a global variable or a local variable prefixed by the static keyword, it will allocate space for it in RAM, giving it a permanent (static) address. This is in contrast to auto variables which are allocated on the stack.
Exist for the Entire Life of the Program
A static variable is created when the program first starts and stays alive until the program exits. In an embedded system, this means that static variables always exist—the only time they disappear is when power is removed.
Global Variables are Always static
A global variable (declared outside of any function) has no choice—it must always be static. You cannot use the auto keyword with a global variable.
2
3
4
5
int main(void)
{
...
A Variable Declared as Static Inside a Function
Static variables within functions behave much like global variables in that they have a permanent address in memory. However, if you try to access the variable outside of the function, the compiler will complain that the variable doesn't exist. A static variable inside a function may only be accessed from within the function, but it will retain its value across function calls just like a global variable. This could be used to keep track of how many times a function has been called from within the function and without the use of global variables.
Function Parameters Cannot be Static With Some Compilers
Unlike variables declared within a function, some compilers, including MPLAB® XC16, do not allow function parameters to be static under any circumstances—they must always be automatic. This isn't generally a problem since MPLAB XC16 passes parameters very efficiently through the working registers. However, MPLAB C18 does allow static parameters, which can be accessed more efficiently than automatic variables on that architecture. This can be advantageous with the relatively small memory size of the PIC18 compared to other processors that are typically programmed in C.
In the following example, a will remember its value from the last time the function was called. If given an initial value, it is only initialized when first created, not during each function call.
2
3
4
5
6
7
{
static int a = 0;
...
a += x;
return a;
}