如何在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