为什么在 C 中声明变量或函数是静态的? [英] Why declare a variable or function static in C?

查看:30
本文介绍了为什么在 C 中声明变量或函数是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 static 的作用,但不明白我们为什么要使用它.只是为了保留抽象层吗?

I understand what static does, but not why we use it. Is it just for keeping the abstraction layer?

推荐答案

在 C 中使用 static 有几个原因.

There are a few reasons to use static in C.

与函数一起使用时,是的,目的是创建抽象.C 源代码文件范围的原始术语是翻译单元".只能从同一翻译单元内访问静态函数.这些静态函数类似于 C++ 中的私有方法,可以自由解释(在这个类比中,一个翻译单元定义一个类).

When used with functions, yes the intention is for creating abstraction. The original term for the scope of a C source code file was "translation unit." The static functions may only be reached from within the same translation unit. These static functions are similar to private methods in C++, liberally interpreted (in that analogy, a translation unit defines a class).

全局级别的静态数据也无法从翻译单元外部访问,这也用于创建抽象.此外,所有静态数据都初始化为零,因此可以使用 static 来控制初始化.

Static data at a global level is also not accessible from outside the translation unit, and this is also used for creating an abstraction. Additionally, all static data is initialized to zero, so static may be used to control initialization.

本地(自动")变量级别的静态用于抽象函数的实现,该函数在调用之间保持状态,但避免在翻译单元范围内使用变量.同样,由于静态限定,变量被初始化为零.

Static at the local ("automatic") variable level is used to abstract the implementation of the function which maintains state across calls, but avoids using a variable at translation unit scope. Again, the variables are initialized to zero due to static qualification.

这篇关于为什么在 C 中声明变量或函数是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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