Instructions
Declare a Static Variable
1Know that static variables are always declared inside a C function, but unlike other variables, their values continue to exist and are retained, even after the function exits.
2
Declare a static variable by using the same syntax as you would to declare a normal local variable, but precede the declaration with the word static, like this:
static int sum = 0;
3
Expect initialization to happen only the first time you call the function. Subsequent times, the previous value will still be there. If you omit the initialization, it will automatically be initialized to 0.
4
Use the variable in the function like you would any other.
5
Remember that, like any other local variable, a static variable cannot be referred to outside the function. However, if you pass out a pointer to it, the pointer can be dereferenced successfully, since the variable still exists.
Know When to Use Static Variables
1Use a static variable to allow your function to have its own memory that carries over from one call to another. For example, a function that gets and parses the next line of a file might need to internally keep track of where it is in the file.
2
Use a static variable as a way to provide a piece of memory for storing a result. For example, a function to concatenate strings might use a static variable in which to store the result of the concatenation and return a pointer to it. The static variable's memory is constantly available, but will automatically be freed when the program ends, just like any other local variable.
3
Use static variables for a running total or similar accumulation. Consider this example:
int running_total(int num) {
static int sum = 0;
sum += num;
return sum;
}Each time you call this function, it keeps and returns a running total of all numbers passed into it.
SHARE