根据这一规则,我们容易知道,在任何花括号内的静态变量,都是局部静态变量(local static variable),其作用范围受到对应的花括号限制。有一类特殊的静态变量,它们的头顶上没有任何花括号了,而且也没有static关键字的限制,那么我们可以理解为,这类无人约束的变量,其作用范围就是整个工程啦——也就是我们所说的全局变量。还有一类
C语言允许在所有函数的外部定义变量,这样的变量称为全局变量(Global Variable)。全局变量的默认作用域是整个程序,也就是所有的代码文件,包括源文件(.c文件)和头文件(.h文件)。如果给全局变量加上 static 关键字,它的作用域就变成了当前文件,在其它文件中就无效了。我们目前编写的代码都是在一个源文件中...
1#include <stdio.h>2#include <string.h>3#include <stdlib.h>45voidtest_static_local_variable();67intglobal_var =1;//普通全局变量,随着整个程序的结束而消亡。可以在整个程序方法问8//可以在其他.c文件中访问9staticintstatic_global_var =1;//静态全局变量,限定只能在本文件内部访问1011intmain(intar...
1#include <stdio.h>2#include <string.h>3#include <stdlib.h>45voidtest_static_local_variable();67intglobal_var =1;//普通全局变量,随着整个程序的结束而消亡。可以在整个程序方法问8//可以在其他.c文件中访问9staticintstatic_global_var =1;//静态全局变量,限定只能在本文件内部访问1011intmain(intar...
static int i = 5; /* localstaticvariable */ i++; printf("i is %d and count is %d ", i, count); } 编译并执行上述代码时,会产生以下结果 - i is 6 and count is 4 i is 7 and count is 3 i is 8 and count is 2 i is 9 and count is 1 ...
1、static变量存放在静态存储区,在程序整个运行期间都不释放;而auto变量存放在动态存储区,随着生命周期的结束而立即释放。2、static变量只赋值一次,以后就不用赋值;而auto变量在函数每调用一次都要赋初值。3、如果用户不对static变量赋初值,则默认为0或'\0';而auto变量为不确定值。
1.static 局部静态变量 定义在函数内部的变量称为局部变量(Local Variable),它的作用域仅限于函数内部, 离开该函数后就是无效的,生命周期直接结束,再使用就会报错。 而使用 static 修饰的局部静态变量,它的作用域仅限于函数内部, 离开该函数后就是无效的,**生命周期**直到程序结束,举个栗子: ...
(1) a static local variable defines its lifetime in the function as the entire source, but its scope remains the same as that of the automatic variable, and can only be used within the function defining the variable. After exiting the function, you cannot use it even though it still ...
global local static 1 10 2 9 3 8 4 7 5 6 6 5 7 4 8 3 9 2 10 1 3. static的第三个作用是默认初始化为0.其实全局变量也具备这一属性,因为全局变量也存储在静态数据区 在静态数据区,内存中所有的字节默认值都是0x00,某些时候这一特点可以减少程序员的工作量。比如初始化一个稀疏矩阵,我们...
extern char a; // extern variable must be declared before use printf("%c ", a); (void)msg(); return 0; } 程序的运行结果是: A Hello 你可能会问:为什么在 a.c 中定义的全局变量 a 和函数 msg 能在 main.c 中使用?前面说过,所有未加 static 前缀的全局变量和函数都具有全局可见性,其它的源...