什么时候确定使用在C全局变量? [英] When is it ok to use a global variable in C?

查看:259
本文介绍了什么时候确定使用在C全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,有一个在舆论的很多品种在那里,从永不永远封装!(即使是一个单纯的微距!)到这没什么大不了的 - 使用它们时,它比不是更方便。

Apparently there's a lot of variety in opinions out there, ranging from, "Never! Always encapsulate (even if it's with a mere macro!)" to "It's no big deal - use them when it's more convenient than not."

左右。

明确,具体的原因(用一个例子pferably $ P $)

Specific, concrete reasons (preferably with an example)


  • 为什么全局变量是危险

  • 在当前全局变量的的替代方案中使用

  • 存在的那些诱惑不适当地使用全局变量什么选择

  • Why global variables are dangerous
  • When global variables should be used in place of alternatives
  • What alternatives exist for those that are tempted to use global variables inappropriately

虽然这是主观的,我会选择一个答案(对我最好再presents的爱/恨关系每个开发人员应该有全局)和社区会投票给他们略低于。

While this is subjective, I will pick one answer (that to me best represents the love/hate relationship every developer should have with globals) and the community will vote theirs to just below.

我相信新手有这样的参考,但如果另一个答案存在,这是基本相似的你请不要扰乱它是很重要的 - 添加注释或编辑别人的答案

I believe it's important for newbies to have this sort of reference, but please don't clutter it up if another answer exists that's substantially similar to yours - add a comment or edit someone else's answer.

推荐答案

变量应该始终有较小的范围成为可能。背后的论点是,每次增加的范围时你有更多的code,它有可能会修改变量,从而更复杂的解决方案引起的。

Variables should always have the smaller scope possible. The argument behind that is that every time you increase the scope you have more code that potentially modifies the variable, thus more complexity is induced in the solution.

因此​​,很明显,使用全局变量,避免为pferred $ P $如果设计和实施自然允许。由于这一点,我preFER不使用全局变量,除非真正需要他们。

It is thus clear that avoiding using global variables is preferred if the design and implementation naturally allows that. Due to this I prefer not using global variables unless they are really needed.

我不能用永不说法要么,像任何其他概念全局变量在需要时应该使用的工具。我宁愿使用全局变量不是使用一些人工构造(如各地传递指针),这只会掩盖真正的意图。
其中使用全局变量最好的例子就是Singleton模式的实现或在嵌入式系统寄存器访问。

I can not agree with the "never" statement either, Like any other concept global variables are a tool that should be used when needed. I would rather use global variables than use some artificial constructs (like passing pointers around) which would only mask the real intent. Good examples where global variables are used are singleton pattern implementations or register access in embedded systems.

在如何实际检测全局变量过多用法:报检,报验,检验。每当我看到一个全局变量我不得不问自己:这真的需要在全球范围内

On how to actually detect excessive usages of global variables: inspection, inspection, inspection. Whenever I see a global variable I have to ask myself: Is that REALLY needed at a global scope?

这篇关于什么时候确定使用在C全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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