Why people dislike global variables so much while I find them so convenient?

rempas rempas at tutanota.com
Wed Jan 26 07:51:30 UTC 2022


On Tuesday, 25 January 2022 at 12:07:31 UTC, Ola Fosheim Grøstad 
wrote:
> Because the program is larger, there are more locations that 
> could mutate the global state. ("reason" ≈ "prove correct")

Yeah but what if it makes sense for these places to mutate it? 
For example, I'm making a parser for my language and each 
different statement will be parsed from a function that will be 
in a different file. It makes sense for those files to be able to 
mutate some global variables.

> 1. globals are singletons, it becomes difficult to have 
> multiple instance if you later regret having only one instance.
>
> 2. because you need to use locking correctly to prevent 
> multiple threads from mutating the state at once and then you 
> have to prove that your locking strategy is does not lead to 
> starvation or deadlocks.

I don't know about most of this terms and I know only a little 
about multi-threading programming. So thank you, I will make my 
research and this info will come in handy!

> I don't understand what you are trying to say here.
>
> The global variable should be local to the object file. The 
> accessor functions can be globally accessible.

Actually the example I made with the parser will explain that 
too. I want some specific files to be able to access the global 
variables. If they are only local to a file then they don't help 
me a lot and I still have to use pointers to modify that specific 
data.

> Passing one pointer isn't particularly expensive. What 
> (non-TLS) globals save you on some CPUs are registers and time 
> spent on allocation.

Thanks! Why talking about allocations tho? We will not need to 
allocate any memory to pass a pointer to a function and then 
deference it. Of course if you think that you will push it to the 
stuck in your main function and then you will call all the other 
functions in the top.

> For instance,  using globals can make sense in embedded 
> programming on tiny CPUs with very little RAM.

Well yeah! However, embedded programming is an advanced topic so 
I suppose different rules apply there anyways...


> https://dlang.org/spec/attribute.html#gshared

Thanks a lot!!


More information about the Digitalmars-d mailing list