在C/ c++中,全局变量像我的教授认为的那样糟糕吗?


当前回答

是的,因为如果你让不称职的程序员使用它们(阅读90%,尤其是科学家),你最终会得到600多个全局变量分布在20多个文件和一个12000行的项目中,其中80%的函数采用void,返回void,完全在全局状态下运行。

除非你了解整个项目,否则你很快就不可能在任何一个点上理解正在发生什么。

其他回答

绝对不是。但是滥用它们……这很糟糕。

出于某种原因而无意识地删除它们只是……盲目的。除非您知道其优点和缺点,否则最好避免使用全局变量,并按照您学到的方法进行操作,但全局变量并没有什么隐含的错误。当你了解了利弊后,最好自己做决定。

不,他们一点都不坏。你需要查看编译器生成的(机器)代码来做出判断,有时使用局部变量比使用全局变量要糟糕得多。还要注意,在局部变量上添加“static”基本上是使其成为全局变量(并产生真正的全局变量可以解决的其他丑陋问题)。“局部全局变量”尤其糟糕。

全局变量还可以让你完全控制内存的使用,这在局部变量中要困难得多。如今,这只在内存相当有限的嵌入式环境中才重要。在假定嵌入式环境与其他环境相同并假定编程规则全面相同之前,需要了解一些事情。

It is good that you question the rules being taught, most of them are not for the reasons you are being told. The most important lesson though is not that this is a rule to carry with you forever, but this is a rule required to honor in order to pass this class and move forward. In life you will find that for company XYZ you will have other programming rules that you in the end will have to honor in order to keep getting a paycheck. In both situations you can argue the rule, but I think you will have far better luck at a job than at school. You are just another of many students, your seat will be replaced soon, the professors wont, at a job you are one of a small team of players that have to see this product to the end and in that environment the rules developed are for the benefit of the team members as well as the product and the company, so if everyone is like minded or if for the particular product there is good engineering reason to violate something you learned in college or some book on generic programming, then sell your idea to the team and write it down as a valid if not the preferred method. Everything is fair game in the real world.

如果你遵循学校或书本上教给你的所有编程规则,那么你的编程生涯将非常有限。你很可能会生存下来,并拥有一个富有成效的事业,但你所能获得的环境的广度和宽度将是极其有限的。如果你知道规则是如何存在的,为什么会存在,并且能够捍卫它,那很好,如果你的理由只是“因为我的老师这么说”,那就不太好了。

请注意,这样的话题经常在工作场所被争论,并且将继续存在,随着编译器和处理器(以及语言)的发展,这些类型的规则也在发展,如果不捍卫你的立场,可能会被持不同意见的人教训一课,你就不会前进。

与此同时,那个说话声音最大或拿着最大棍子的人说什么,你就做什么(直到你是那个喊得最大、拿着最大棍子的人)。

安全并不意味着任何一个可以操纵变量声明的全局,为这一解释这个例子中如果你有平衡作为一个全局变量在你们银行程序用户函数可以操纵以及银行职员也可以操纵这这是一个问题只有用户应该考虑到只读和退出函数,而是银行的职员可以添加量当用户亲自给的现金在桌子上。这就是它的运作方式

全局变量的使用实际上取决于需求。它的优点是减少了重复传递值的开销。

但是你的教授是对的,因为它会引起安全问题,所以应该尽可能避免使用全局变量。全局变量还会产生一些问题,有时难以调试。

例如:-

变量值在运行时被修改的情况。此时,很难确定是哪部分代码在什么条件下修改了它。

如果您的代码有可能在最高法院审判期间被严格审查,那么您应该确保避免使用全局变量。

请看这篇文章: 漏洞百出的酒精测试仪代码反映了源代码审查的重要性

There were some problems with the style of the code that were identified by both studies. One of the stylistic issues that concerned the reviewers was the extensive use of unprotected global variables. This is considered poor form because it increases the risk that the program state will become inconsistent or that values will be inadvertently modified or overwritten. The researchers also expressed some concern about the fact that decimal precision is not maintained consistently throughout the code.

伙计,我敢打赌那些开发人员希望他们没有使用全局变量!