如何在C中使用靜態變量
在函數內部,您可以初始化一個靜態變量使用static
關鍵詞。
我說“在函數內部”,因為默認情況下全局變量是靜態的,因此無需添加關鍵字。
什麼是靜態變量?如果未指定初始值,則將靜態變量初始化為0,並在函數調用期間保留該值。
考慮以下功能:
int incrementAge() {
int age = 0;
age++;
return age;
}
如果我們打電話incrementAge()
一次,我們會得到1
作為返回值。如果我們多次調用它,我們總是會得到1,因為age
是一個局部變量,它被重新初始化為0
在每個單個函數調用上。
如果將函數更改為:
int incrementAge() {
static int age = 0;
age++;
return age;
}
現在,每次調用此函數時,我們將獲得一個遞增的值:
printf("%d\n", incrementAge());
printf("%d\n", incrementAge());
printf("%d\n", incrementAge());
會給我們
1
2
3We can also omit initializing age
to 0 in static int age = 0;
, and just write static int age;
because static variables are automatically set to 0 when created.
We can also have static arrays. In this case, each single item in the array is initialized to 0:
int incrementAge() {
static int ages[3];
ages[0]++;
return ages[0];
}
Download my free C Handbook
More clang tutorials:
- Introduction to the C Programming Language
- C Variables and types
- C Constants
- C Operators
- C Conditionals
- How to work with loops in C
- Introduction to C Arrays
- How to determine the length of an array in C
- Introduction to C Strings
- How to find the length of a string in C
- Introduction to C Pointers
- Looping through an array with C
- Booleans in C
- Introduction to C Functions
- How to use NULL in C
- Basic I/O concepts in C
- Double quotes vs single quotes in C
- How to return a string from a C function
- How to solve the implicitly declaring library function warning in C
- How to check a character value in C
- How to print the percentage character using `printf()` in C
- C conversion specifiers and modifiers
- How to access the command line parameters in C
- Scope of variables in C
- Can you nest functions in C?
- Static variables in C
- C Global Variables
- The typedef keyword in C
- C Enumerated Types
- C Structures
- C Header Files
- The C Preprocessor