什么是“静态”?在C中意味着什么? [英] What does "static" mean in C?

查看:73
本文介绍了什么是“静态”?在C中意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在C代码的不同地方看到了 static 这个词;这就像C#中的静态函数/类(实现在对象之间共享)吗?

I've seen the word static used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?

推荐答案


  1. 函数内部的静态变量在调用之间保持其值。

  2. 仅在其声明的文件中看到静态全局变量或函数

(1)是如果您是新手,那么您会遇到更多的外国话题,因此这里有个例子:

(1) is the more foreign topic if you're a newbie, so here's an example:

#include <stdio.h>

void foo()
{
    int a = 10;
    static int sa = 10;

    a += 5;
    sa += 5;

    printf("a = %d, sa = %d\n", a, sa);
}


int main()
{
    int i;

    for (i = 0; i < 10; ++i)
        foo();
}

此打印:

a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60

这在函数需要保持某些状态的情况下非常有用之间的调用,并且您不想使用全局变量。但是要当心,应该非常谨慎地使用此功能-它使您的代码不是线程安全的并且更难以理解。

This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.

(2)被广泛用作访问控制功能。如果您具有实现某些功能的.c文件,则通常仅向用户公开一些公共功能。其其余功能应设为 static ,以便用户无法访问它们。

(2) Is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static, so that the user won't be able to access them. This is encapsulation, a good practice.

引用 Wikipedia


在C语言中,静态
与全局变量和
函数一起使用,将其范围设置为包含
的文件。在局部变量中,静态
用于将变量
存储在静态分配的内存
中,而不是自动分配的
内存中。虽然语言不是
决定
类型的内存的实现方式,但是静态分配的
内存通常在编译
时保留在程序的数据
段中,而自动分配的
内存通常是作为临时调用堆栈实现的

In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.

然后回答第二个问题问题,这与C#中的情况不同。

And to answer your second question, it's not like in C#.

在C ++中, static 也用于定义类属性(在相同类的所有对象之间共享)和方法。在C语言中没有类,因此此功能无关。

In C++, however, static is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.

这篇关于什么是“静态”?在C中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆