c - 关键字 static 对变量和函数的作用不同的确切原因是什么

标签 c memory static static-variables static-functions

如果我们在变量前面使用静态,它的值在函数调用之间的程序执行的整个周期内保持不变。但是如果我们将 static 与函数一起使用,它们将成为声明它们的文件的局部变量。我知道是这样,但我想知道到底是为什么?为什么 static 有两种行为方式?我试过网络但没有运气,请解释一下!另外请告诉我静态函数将存储在内存中的什么位置,我个人认为它在堆栈中!

最佳答案

事实上,当关键字static用作链接说明符时,它对函数和变量具有相同的含义,即用关键字static声明的命名空间中的函数和变量具有内部链接。

来自C++标准(3.5程序和链接)

3 A name having namespace scope (3.3.6) has internal linkage if it is the name of — a variable, function or function template that is explicitly declared static

静态函数的存储方式与其他函数相同,只是它们的名称不作为外部名称导出。

此关键字为变量重载。它还表示静态存储持续时间。这就是您在帖子中所说的内容。

来自 C++ 标准(3.7.1 静态存储持续时间)

1 All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program (3.6.2, 3.6.3).

3 The keyword static can be used to declare a local variable with static storage duration.

4 The keyword static applied to a class data member in a class definition gives the data member static storage duration.

相对于类的成员,C++ 中的关键字 static 还有第三种含义(在 C 中没有类,因此这对 C 无效)。

1 A data or function member of a class may be declared static in a class definition, in which case it is a static member of the class.

关于c - 关键字 static 对变量和函数的作用不同的确切原因是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25602757/

相关文章:

c - 使用 Fiddle 将 RUBY 数组传递到 C DLL

带有来自另一个常量数组的变量的常量数组

r - 在 Linux 中替代 R 的 `memory.size()`?

Java减少内存使用

具有函数指针常量数组的 C++ 模板化静态类

c - Linux 上的 wprintf UTF16(应该是 UTF8)?

c++ - 有什么理由使用 switch 语句而不是 if 和 elseif 字符串吗?

c++ - malloc/new 是否从缓存或 RAM 返回内存块?

java - 在Android widget 类中使用静态成员是否正常?

c - 什么是 C 中的 "static"函数?