函数内部静态变量的使用
我已经编写 C 代码很多年了,但最近我遇到了一个我从未使用过的功能:函数内的静态变量。因此,我想知道您使用此功能的方式有哪些,这是正确的设计决策。
例如,
int count(){
static int n;
n = n + 1;
return n;
}
这是一个糟糕的设计决策。为什么?因为稍后您可能想要减少计数,这将涉及更改函数参数,更改所有调用代码,...
希望这足够清楚, 谢谢!
I have been writing C code for many years, but I recently came accross a feature that I have never used: a static variable inside a function. Therefore, I was wondering what are some ways that you have used this feature and it was the right design decision.
E.g.
int count(){
static int n;
n = n + 1;
return n;
}
is a BAD design decision. why? because later you might want to decrement the count which would involve changing the function parameters, changing all calling code, ...
Hopefully this is clear enough,
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我在测试代码中使用静态变量来延迟初始化状态。在生产代码中使用静态局部变量充满危险,并可能导致微妙的错误。似乎(至少在我通常处理的代码中)几乎任何以单线程代码块开始的代码都有一个令人讨厌的习惯,即最终在并发情况下工作。在并发环境中使用静态变量可能会导致难以调试的问题。这样做的原因是因为由此产生的状态变化本质上是一个隐藏的副作用。
I have used static variables in test code for lazy initialization of state. Using static local variables in production code is fraught with peril and can lead to subtle bugs. It seems (at least in the code that I generally work on) that nearly any bit of code that starts out as a single-threaded only chunk of code has a nasty habit of eventually ending up working in a concurrent situation. And using a static variable in a concurrent environment can result in difficult issues to debug. The reason for this is because the resulting state change is essentially a hidden side effect.
我使用静态变量作为控制另一个线程执行的方法。
例如,线程#1(主线程)首先声明并初始化一个控制变量,例如:
然后它开始执行线程#2,该线程将执行一些工作,直到线程#1决定停止它:
I have used static variables as a way to control the execution of another thread.
For instance, thread #1 (the main thread) first declares and initializes a control variable such as:
and then it starts the execution of thread #2, which is going to do some work until thread #1 decides to stop it:
有一个突出的例子,您非常需要保持
静态
来保护关键部分,即互斥锁。作为 POSIX 线程的示例:这不适用于
auto
变量。POSIX 有用于互斥体、条件和一次变量的静态初始值设定项。
There is one prominent example that you very much need to be
static
for protecting critical sections, namely a mutex. As an example for POSIX threads:This wouldn't work with an
auto
variable.POSIX has such
static
initialzers for mutexes, conditions and once variables.