在C/ c++中,全局变量像我的教授认为的那样糟糕吗?
当前回答
绝对不是。但是滥用它们……这很糟糕。
出于某种原因而无意识地删除它们只是……盲目的。除非您知道其优点和缺点,否则最好避免使用全局变量,并按照您学到的方法进行操作,但全局变量并没有什么隐含的错误。当你了解了利弊后,最好自己做决定。
其他回答
我的教授曾经说过这样的话:使用全局变量是可以的,如果你使用正确的话。我不认为我能正确地使用它们,所以我很少使用它们。
全局变量在小程序中很好,但如果在大程序中以同样的方式使用就很糟糕了。
这意味着你可以很容易地在学习中养成使用它们的习惯。这就是你的教授想要保护你的东西。
当你更有经验的时候,在他们没事的时候学习就更容易了。
在多线程应用程序中,使用局部变量代替全局变量以避免竞态条件。
当多个线程访问共享资源时,至少有一个线程对数据有写访问权,就会发生竞争条件。然后,程序的结果是不可预测的,它取决于不同线程访问数据的顺序。
更多信息请访问https://software.intel.com/en-us/articles/use-intel-parallel-inspector-to-find-race-conditions-in-openmp-based-multithreaded-code
不,他们一点都不坏。你需要查看编译器生成的(机器)代码来做出判断,有时使用局部变量比使用全局变量要糟糕得多。还要注意,在局部变量上添加“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.
如果你遵循学校或书本上教给你的所有编程规则,那么你的编程生涯将非常有限。你很可能会生存下来,并拥有一个富有成效的事业,但你所能获得的环境的广度和宽度将是极其有限的。如果你知道规则是如何存在的,为什么会存在,并且能够捍卫它,那很好,如果你的理由只是“因为我的老师这么说”,那就不太好了。
请注意,这样的话题经常在工作场所被争论,并且将继续存在,随着编译器和处理器(以及语言)的发展,这些类型的规则也在发展,如果不捍卫你的立场,可能会被持不同意见的人教训一课,你就不会前进。
与此同时,那个说话声音最大或拿着最大棍子的人说什么,你就做什么(直到你是那个喊得最大、拿着最大棍子的人)。
安全并不意味着任何一个可以操纵变量声明的全局,为这一解释这个例子中如果你有平衡作为一个全局变量在你们银行程序用户函数可以操纵以及银行职员也可以操纵这这是一个问题只有用户应该考虑到只读和退出函数,而是银行的职员可以添加量当用户亲自给的现金在桌子上。这就是它的运作方式