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

查看:93
本文介绍了“静态"是什么意思?在 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
", 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.

引用维基百科:

在C编程语言中,静态与全局变量一起使用和函数将其范围设置为包含文件.在局部变量中,static 用于存储变量在静态分配的内存中而不是自动分配的记忆.虽然语言不规定任何一个的实施内存类型,静态分配内存通常保留在数据中编译时的程序段时间,而自动分配的内存通常是实现为瞬态调用堆栈.

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天全站免登陆