📜  内部静态变量与外部静态变量与 C 中的示例

📅  最后修改于: 2021-09-10 03:01:52             🧑  作者: 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 基础课程