C言語でのstaticキーワードの利用方法は何ですか。
C言語では、staticキーワードには主に2つの用途があります。
- 静的
以下が例です:
#include <stdio.h>
void test() {
static int count = 0;
count++;
printf("count: %d\n", count);
}
int main() {
test(); // 输出:count: 1
test(); // 输出:count: 2
test(); // 输出:count: 3
return 0;
}
上記の例では、test関数を呼び出すたびに、countの値が増加し、前回の呼び出し結果が保持されます。これは、countがstaticとして宣言されているため、関数の実行後も破棄されないためです。
- 静的
ここに一つ例を示します:
// file1.c
#include <stdio.h>
static int count = 0;
void increment() {
count++;
}
void display() {
printf("count: %d\n", count);
}
// file2.c
#include <stdio.h>
extern void increment();
extern void display();
int main() {
increment();
increment();
display(); // 输出:count: 2
return 0;
}
上記の例では、countはstaticとして宣言されているため、file1.cでのみアクセスできます。file2.cでは、increment関数とdisplay関数をexternキーワードを使用して宣言し、main関数でこれらの関数を呼び出してcountの値を操作および表示できます。