租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

c语言static的作用有哪几种,c语言static的作用域

发布时间:2023-09-12 07:50:41

c语言static的作用有哪几种

C语言中的static关键字有以下几种作用:
1. 限制作用域:在函数内部使用static修饰局部变量,可以将其作用域限制在函数内部,使得变量在函数履行完后依然保持其值,且对其他函数不可见。
```c
void func() {
static int count = 0;
count++;
printf("count: %d ", count);
}
int main() {
func(); // 输出: count: 1
func(); // 输出: count: 2
return 0;
}
```
2. 保护数据:在C文件内使用static修饰全局变量,可以将其作用域限制在当前文件内部,使得其他文件没法访问该变量。
```c
// file1.c
static int count = 0;
// file2.c
extern int count; // 编译毛病,没法访问file1.c中的count变量
```
3. 隐藏函数:在C文件内使用static修饰函数,可以将其作用域限制在当前文件内部,使得其他文件没法调用该函数。
```c
// file1.c
static void func() {
printf("Hello, World! ");
}
// file2.c
extern void func(); // 编译毛病,没法调用file1.c中的func函数
```
4. 提供持久性:在静态变量中使用static修饰,可使得变量在程序履行进程中保持其值不变,且对其他函数不可见。
```c
int func() {
static int count = 0;
count++;
return count;
}
int main() {
printf("%d ", func()); // 输出: 1
printf("%d ", func()); // 输出: 2
return 0;
}
```