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

Mark smarksc at gmail.com
Wed Jan 26 11:52:13 UTC 2022


On Tuesday, 25 January 2022 at 09:53:25 UTC, rempas wrote:
> It is known that people dislike global variables and the reason 
> is that they make the code harder to debug. In my experience 
> tho, it is the exact opposite. When I have a variable that I 
> must pass down to 5-6 functions, I find it much easier to make 
> it global rather than having it been passed in all the 
> functions that need it. This practice also makes my function 
> signatures looking much cleaner. Yeah, one variable will not 
> make a difference but in my project, I have about 2-3 variables 
> that need to be passed down to a lot of functions so I only 
> think that it makes sense to use them as globals. Another 
> problem is the case that I'll introduce a new variable that 
> needs to also be passed in most of my functions. What happens 
> then? Let's say I will have 20 functions at the time. I have to 
> change both the function signature and all the other places in 
> code that call this function. The latter can be easily done 
> with a quick "search and replace" in my text editor but still, 
> it's a tedious thing to do.
>
> So can someone make examples about how global variables can 
> mess me up. I know that probably everyone here has more 
> personal experience than me so I really want to learn why 
> global variables are considered so harmful.

Some examples of global variables that are frequently used:
1) C has an implicit global variable in all programs - errno.
2) If you are writing `asm` blocks (in C or D), then the 
processor's flags and registers are obviously global variables 
that can affect the function's behavior. At least in D the 
compiler will complain if a function is marked `pure` but has an 
inner `asm` block; the block has to be annotated explicitly with 
`pure`.
3) The language runtime might also be considered as one giant 
global variable. As an example, a function may return 
successfully on one invocation and fail on another despite being 
pure and being invoked with the same parameters, just because a 
memory allocation has failed. Potentially, you could even catch 
and handle OurOfMemoryErrors (something which you aren't supposed 
to do, I think) and change function behavior based on that. 
However, if I'm not mistaken, any issues related to memory 
allocation aren't typically considered a part of the function's 
"contract"; otherwise, `pure` would only be possible if `@nogc` 
is also present.


More information about the Digitalmars-d mailing list