Unix™ Systems Programming [Electronic resources] : Communication, Concurrency, and Threads نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Unix™ Systems Programming [Electronic resources] : Communication, Concurrency, and Threads - نسخه متنی

Prentice Hall

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید










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 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.


    / 276