全局变量不好吗? [英] Are global variables bad?

查看:45
本文介绍了全局变量不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In C/C++, are global variables as bad as my professor thinks they are?

推荐答案

全局变量的问题在于,由于每个函数都可以访问这些变量,因此越来越难以确定哪些函数实际读写了这些变量.

The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.

要了解应用程序的工作原理,您几乎必须考虑修改全局状态的每个函数.这是可以做到的,但随着应用程序的增长,它会变得几乎不可能(或至少完全浪费时间).

To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).

如果你不依赖全局变量,你可以根据需要在不同的函数之间传递状态.这样您就更有可能了解每个函数的作用,因为您不需要考虑全局状态.

If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.

这篇关于全局变量不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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