在C/ c++中,全局变量像我的教授认为的那样糟糕吗?
当前回答
如果您的代码有可能在最高法院审判期间被严格审查,那么您应该确保避免使用全局变量。
请看这篇文章: 漏洞百出的酒精测试仪代码反映了源代码审查的重要性
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.
伙计,我敢打赌那些开发人员希望他们没有使用全局变量!
其他回答
迟早,您将需要更改该变量的设置方式或访问它时发生的情况,或者您只需要查找它被更改的位置。
实际上,不使用全局变量总是更好。只需编写大坝获取和设置方法,并在一天、一周或一个月后当你需要它们时通知你。
全局变量在小程序中很好,但如果在大程序中以同样的方式使用就很糟糕了。
这意味着你可以很容易地在学习中养成使用它们的习惯。这就是你的教授想要保护你的东西。
当你更有经验的时候,在他们没事的时候学习就更容易了。
如果您的代码有可能在最高法院审判期间被严格审查,那么您应该确保避免使用全局变量。
请看这篇文章: 漏洞百出的酒精测试仪代码反映了源代码审查的重要性
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.
伙计,我敢打赌那些开发人员希望他们没有使用全局变量!
我的教授曾经说过这样的话:使用全局变量是可以的,如果你使用正确的话。我不认为我能正确地使用它们,所以我很少使用它们。
全局变量的问题是,由于每个函数都可以访问这些变量,因此越来越难以确定哪些函数实际读写这些变量。
为了理解应用程序是如何工作的,您几乎必须考虑修改全局状态的每个函数。这是可以做到的,但随着应用程序的增长,它将变得越来越困难,几乎不可能(或至少完全浪费时间)。
如果不依赖全局变量,则可以根据需要在不同函数之间传递状态。这样,您就有更好的机会理解每个函数的功能,因为您不需要考虑全局状态。
推荐文章
- cplusplus.com给出的错误、误解或坏建议是什么?
- C多行宏:do/while(0) vs作用域块
- 找出质数最快的算法是什么?
- time_t最终的类型定义是什么?
- 我需要显式处理负数或零时,总和平方数字?
- c++枚举类可以有方法吗?
- 函数名周围的括号是什么意思?
- 用C语言创建自己的头文件
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 如果不是内存地址,C指针到底是什么?
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?