Are global variables bad? [closed]

2018-12-31 00:49发布

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

28条回答
有味是清欢
2楼-- · 2018-12-31 01:25

I usually use globals for values that are rarely changed like singletons or function pointers to functions in dynamically loaded library. Using mutable globals in multithreaded applications tends to lead to hard to track bug so I try to avoid this as a general rule.

Using a global instead of passing an argument is often faster but if you're writing a multithreaded application, which you often do nowadays, it generally doesn't work very well (you can use thread-statics but then the performance gain is questionable).

查看更多
荒废的爱情
3楼-- · 2018-12-31 01:26

Global are good when it comes to configuration . When we want our configuration/changes to have a global impact on entire project.

So we can change one configuration and the changes are directed to entire project . But I must warn you would have to be very smart to use globals .

查看更多
裙下三千臣
4楼-- · 2018-12-31 01:26

In a multi-threaded application, use local variables in place of global variables to avoid a race condition.

A race condition occurs when multiple thread access a shared resource, with at least one thread having a write access to the data. Then, the result of the program is not predictable, and depends on the order of accesses to the data by different threads.

More on this here, https://software.intel.com/en-us/articles/use-intel-parallel-inspector-to-find-race-conditions-in-openmp-based-multithreaded-code

查看更多
萌妹纸的霸气范
5楼-- · 2018-12-31 01:27

Global variables are fine in small programs, but horrible if used the same way in large ones.

This means that you can easily get in the habit of using them while learning. This is what your professor is trying to protect you from.

When you are more experienced it will be easier to learn when they are okay.

查看更多
登录 后发表回答