2.8 Use of Static Variables

Team-FLY

2.8 Use of Static Variables

While care must be taken in using static variables in situations with multiple threads, static variables are useful. For example, a static variable can hold internal state information between calls to a function.

Program 2.5 shows a function called bubblesort along with auxiliary functions for keeping track of the number of interchanges made. The variable count has a static storage class because it is declared outside any block. The static qualifier forces this variable to have internal linkage, guaranteeing that the count variable cannot be directly accessed by any function aside from bubblesort.c . The clearcount function and the interchange in the onepass function are the only code segments that modify count . The internal linkage allows other files linked to bubblesort.c to use an identifier, count , without interfering with the integer count in this file.

The three functions clearcount , getcount and bubblesort have external linkage and are accessible from outside. Notice that the static qualifier for onepass gives this function internal linkage so that it is not accessible from outside this file. By using appropriate storage and linkage classes, bubblesort hides its implementation details from its callers .

Program 2.5 bubblesort.c

A function that sorts an array of integers and counts the number of interchanges made in the process .

 static int count = 0; static int onepass(int a[], int n) { /* return true if interchanges are made */    int i;    int interchanges = 0;    int temp;    for (i = 0; i < n - 1; i++)       if (a[i] > a[i+1]) {          temp = a[i];          a[i] = a[i+1];          a[i+1] = temp;          interchanges = 1;          count++;       }    return interchanges; } void clearcount(void) {    count = 0; } int getcount(void) {    return count; } void bubblesort(int a[], int n) {               /* sort a in ascending order */    int i;    for (i = 0; i < n - 1; i++)       if (!onepass(a, n - i))          break; } 
Exercise 2.20

For each object and function in Program 2.5 give the storage and linkage class where appropriate.

Answer:

The function onepass has internal linkage. The other functions have external linkage. Functions do not have a storage class. The count identifier has internal linkage and static storage. All other variables have no linkage and automatic storage. (See Section A.5 for additional discussion about linkage.)

Section 2.9 discusses a more complex use of static variables to approximate object-oriented behavior in a C program.

Team-FLY


Unix Systems Programming
UNIX Systems Programming: Communication, Concurrency and Threads
ISBN: 0130424110
EAN: 2147483647
Year: 2003
Pages: 274

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net