Книга: Advanced PIC Microcontroller Projects in C

4.1.6 Static Function Variables

4.1.6 Static Function Variables

Normally, variables declared at the beginning of a program, before the main program, are global, and their values can be accessed and modified by all parts of the program. Declaring a variable used in a function as global ensures that its value is retained from one call of the function to another, but this also undermines the variable’s privacy and reduces the portability of the function to other applications. A better approach is to declare such variables as static. Static variables are mainly used in function definitions. When a variable is declared as static, its value is retained from one call of the function to another. In the example code that follows, variable k is declared as static and initialized to zero. This variable is then incremented before exiting from the function, and the value of k remains in existence and holds its last value on the next call to the function (i.e., on the second call to the function the value of k will be 1):

void Cnt(void) {
 static int k = 0; // Declare k as static
 ..................
 ..................
 k++; // increment k
}

Оглавление книги


Генерация: 1.701. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз