📜  内部静态变量与外部静态变量的对比

📅  最后修改于: 2021-05-25 21:34:59             🧑  作者: Mango

静态变量可以是内部变量,也可以是外部变量,具体取决于声明的位置。静态变量存储在初始化的数据段中。

内部静态变量:内部静态变量定义为具有静态变量的变量,这些变量在函数内部声明并一直扩展到特定函数的末尾。

句法:

main( ) 
{
  static datatype variable;
  // other statements
}

例子:

// C program to demonstrate
// Internal Static Variables
  
#include 
  
int value();
  
int main()
{
    printf("%d", value());
    return 0;
}
  
int value()
{
    static int a = 5;
    return a;
}
输出:
5

外部静态变量:外部静态变量是在函数外部声明并为整个文件/程序全局设置的变量。

句法:

static datatype variable;

main()
{
  statements
}

function1()
{
  statements
}

例子:

// C program to demonstrate
// External Static Variables
  
#include 
  
int add(int, int);
  
static int a = 5;
  
int main()
{
    int c;
    printf("%d", add(a, c));
}
  
int add(int c, int b)
{
    b = 5;
    c = a + b;
    return c;
}
输出:
10

内部静态变量和外部静态变量之间的区别:

Parameter Internal Static Variables External Static Variables
Keyword ”static” ”static”
Linkage Internal static variable has no linkage. External static variables has internal linkage.
Declaration Internal static variables are declared within the main function External static variables are declared above the main function.
Comparison Internal static variables are similar to auto(local) variables. External static variables are similar to global(external) variables.
Visibility Internal static variables are active(visibility) in the particular function. External Static variables are active(visibility)throughout the entire program.
Lifetime Internal static variables are alive(lifetime) until the end of the function. External static variables are alive(lifetime) in the entire program.
Scope Internal static variables has persistent storage with block scope(works only within a particular block or function). External static variables has permanent storage with file scope(works throughout the program).
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。