Cprogramming 简明教程

Static Keyword in C

What is static Keyword in C?

static keyword in Cstorage class 说明符之一,它具有基于使用上下文的不同含义。

The static keyword in C is one of the storage class specifiers which has different meanings based on the context in which it is used.

static ”关键字用于声明静态变量和定义静态函数。当声明为 “static” 时,变量表示静态存储类。

The "static" keyword is used to declare a static variable as well as to define a static function. When declared as "static", a variable represents a static storage class.

static function 仅可在其中定义的程序文件中(具有 “.c” 扩展名)内使用。不能使用 “extern” 关键字将静态函数导入另一个文件。

A static function is available only inside the program file (with ".c" extension) in which it is defined. One cannot use the "extern" keyword to import a static function into another file.

Uses of static Keyword

以下是静态关键字的不同用法

The following are the different uses of the static keyword

  1. Static Local Variable: When a local variable is declared with the static keyword, its lifetime will be till the end of the program and it retains the value between the function calls.

  2. Static Global Variable: When a global variable is declared with the static keyword, it can only be accessed within the same file. It is useful when you want to make a global variable as a private global variable to the file in which it is declared.

  3. Static Functions: When you function is declared as a static function, its scope will be limited to the file in which the function is declared. You cannot access the function in other files.

Static Variables (static Keyword with Variables)

When a variable is declared as static, it is initialized only once 。编译器会将变量保留到程序结束。 static variable 也用于存储应该在多个函数之间共享的数据。

When a variable is declared as static, it is initialized only once. The compiler persists with the variable till the end of the program. A static variable is also used to store data that should be shared between multiple functions.

以下是在静态变量方面需要注意的一些重要事项 −

Here are some of the important points to note regarding a static variable −

  1. The compiler allocates space to the static variable in computer’s main memory.

  2. Unlike auto, a static variable is initialized to zero and not garbage.

  3. A static variable is not re-initialized on every function call, if it is declared inside a function.

  4. A static variable has local scope.

Example of static Keyword with Variables

在以下示例中,counter() 函数中的变量 “x” 被声明为静态。当第一次调用 counter() 函数时,它被初始化为 “0”。在每次后续调用中,它不会被重新初始化,而是保留较早的值。

In the following example, the variable "x" in the counter() function is declared as static. It is initialized to "0" when the counter() function is called for the first time. On each subsequent call, it is not re-initialized; instead it retains the earlier value.

#include <stdio.h>

int counter();

int main() {

   counter();
   counter();
   counter();
   return 0;
}

int counter() {
   static int x;
   printf("Value of x as it enters the function: %d\n", x);
   x++;
   printf("Incremented value of x: %d\n", x);
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Value of x as it enters the function: 0
Incremented value of x: 1
Value of x as it enters the function: 1
Incremented value of x: 2
Value of x as it enters the function: 2
Incremented value of x: 3

静态变量类似于全局变量,因为它们都初始化为 0(对于数字类型)或 null pointers (对于 pointers ),除非显式分配。但是,静态变量的范围被限制为其中声明的函数或块。

A static variable is similar to a global variable, as both of them, are initialized to 0 (for numeric types) or null pointers (for pointers) unless explicitly assigned. However, the scope of the static variable is restricted to the function or block in which it is declared.

Static Functions (static Keyword with Functions)

默认情况下,编译器将每个 function 视为全局函数。可以在程序内的任何地方访问它们。

By default, every function is treated as global function by the compiler. They can be accessed anywhere inside a program.

如果在定义中以关键字“static”作为前缀,我们得到一个范围限于其对象文件(以“.c”扩展名保存的程序的编译版本)的静态函数。这意味着静态函数仅在其对象文件中可见。

When prefixed with the keyword "static" in the definition, we get a static function that has a scope limited to its object file (the compiled version of a program saved with ".c" extension). This means that the static function is only visible in its object file.

可以在函数名称前放置关键字“static”来声明一个静态函数。

A static function can be declared by placing the keyword "static" before the function name.

Example of static Keyword with Function (in Multiple Files)

使用 CodeBlocks IDE 打开一个控制台应用程序。添加两个文件“file1.c”和“main.c”。这些文件的内容如下−

Open a console application with the CodeBlocks IDE. Add two files "file1.c" and "main.c". The contents of these files are given as follows −

file1.c ” 的内容 −

Contents of "file1.c" −

static void staticFunc(void) {
   printf("Inside the static function staticFunc() ");
}

main.c ” 的内容 −

Contents of "main.c" −

#include <stdio.h>
#include <stdlib.h>

int main() {

   staticFunc();
   return 0;
}

现在,如果构建上述控制台应用程序项目,那么我们将收到一条错误,即“对 staticFunc() 的引用未定义”。这是因为函数 staticFunc() 是一个静态函数,它只在其对象文件中可见。

Now, if the above console application project is built, then we will get an error, i.e., "undefined reference to staticFunc()". This happens as the function staticFunc() is a static function and it is only visible in its object file.

Example of static Keyword with Function (in the Same File)

以下程序演示了静态函数在 C 程序中的工作方式 −

The following program demonstrates how static functions work in a C program −

#include <stdio.h>

static void staticFunc(void){
   printf("Inside the static function staticFunc() ");
}

int main(){

   staticFunc();
   return 0;
}

以上程序的输出如下:

The output of the above program is as follows −

Inside the static function staticFunc()

在上述程序中,函数 staticFunc() 是一个静态函数,用于打印“Inside the static function staticFunc()”。main() 函数调用 staticFunc()。此程序可以正确工作,因为静态函数仅从其自身的对象文件中调用。

In the above program, the function staticFunc() is a static function that prints "Inside the static function staticFunc()". The main() function calls staticFunc(). This program works correctly as the static function is called only from its own object file.

Example of static Keyword with Multiple Functions

您可以在同一个对象文件中拥有多个静态函数,如下例所示 −

You can have multiple static functions in the same object file, as illustrated in the following example −

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

// define the static function
static int square( int num){
   return num * num;
}

static void voidfn(){
   printf ("From inside the static function.\n");
}

static int intfn(int num2){
   return sqrt(num2);
}

int main(){

   int n1, val;
   n1 = 16;
   val = square(n1);	// Call voidfn static function

   printf("The square of the %d : %d\n", n1, val);
   voidfn();		// Call intfn static function
   val = intfn(n1);
   printf("The square root of the %d : %d\n", n1, val);

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

The square of the 16: 256
From inside the static function.
The square root of the 16: 4