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:12

Global variables are bad, if they allow you to manipulate aspects of a program that should be only modified locally. In OOP globals often conflict with the encapsulation-idea.

查看更多
无色无味的生活
3楼-- · 2018-12-31 01:14

I think your professor is trying to stop a bad habit before it even starts.

Global variables have their place and like many people said knowing where and when to use them can be complicated. So I think rather than get into the nitty gritty of the why, how, when, and where of global variables your professor decided to just ban. Who knows, he might un-ban them in the future.

查看更多
其实,你不懂
4楼-- · 2018-12-31 01:14

Absolutely not. Misusing them though... that is bad.

Mindlessly removing them for the sake of is just that... mindless. Unless you know the advanatages and disadvantages, it is best to steer clear and do as you have been taught/learned, but there is nothing implicitly wrong with global variables. When you understand the pros and cons better make your own decision.

查看更多
几人难应
5楼-- · 2018-12-31 01:14

Yes, because if you let incompetent programmers use them (read 90% especially scientists) you end up with 600+ global variable spread over 20+ files and a project of 12,000 lines where 80% of the functions take void, return void, and operate entirely on global state.

It quickly becomes impossible to understand what is going on at any one point unless you know the entire project.

查看更多
听够珍惜
6楼-- · 2018-12-31 01:16

My professor used to say something like: using global variables are okay if you use them correctly. I don't think I ever got good at using them correctly, so I rarely used them at all.

查看更多
梦该遗忘
7楼-- · 2018-12-31 01:17

Global variables should only be used when you have no alternative. And yes, that includes Singletons. 90% of the time, global variables are introduced to save the cost of passing around a parameter. And then multithreading/unit testing/maintenance coding happens, and you have a problem.

So yes, in 90% of the situations global variables are bad. The exceptions are not likely to be seen by you in your college years. One exception I can think off the top of my head is dealing with inherently global objects such as interrupt tables. Things like DB connection seem to be global, but ain't.

查看更多
登录 后发表回答