Author Topic: Global variables - Evil or not  (Read 7612 times)

0 Members and 1 Guest are viewing this topic.

Offline JesterTopic starter

  • Frequent Contributor
  • **
  • Posts: 859
  • Country: ca
Global variables - Evil or not
« on: October 20, 2022, 05:47:08 pm »
Context:
1) I'm not a programmer I just dabble in C and c++ to a small extent.
2) Embedded application running on a smallish uC for example a small sub module in a automobile, for example: bool wipersOn = false;

I appreciate a global variable in some large program for some large company for example American Airlines would probably be a really bad idea.

The moment you google "global variable" half the comments are DON'T DO IT you will burn in hell.

I have used global variables forever and have never had any issues. Am I missing something?
 

Offline JPortici

  • Super Contributor
  • ***
  • Posts: 3469
  • Country: it
Re: Global variables - Evil or not
« Reply #1 on: October 20, 2022, 05:58:48 pm »
most of my global variables are actually global so that i can inspect them at any time (so are declared global for convenience)
a little few are actually global so they can be accessed easily, but they always are written by one process, read by many... or the processes that can perform a write are not preempted so there is no chance that two writes happen simultaneously.

The problem as i understand it is when the global variable is read while it's being written too, or it can be written by two or more actors. Especially if the read/write is not atomic (think reading/writing 32bit on a 8/16 bit machine) If you can make it sure that it doesn't happen, then no issue for me.
the DON'T DO IT is because too many programmers don't understand this simple concept (with not so simple consequences)
And writing accessory functions can have other benefits as well, such as including the range check for the new value

Some times you cannot escape from globals anyway (shared memory, memory at fixed locations, ...)
 
The following users thanked this post: Jester

Offline Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11694
  • Country: my
  • reassessing directives...
Re: Global variables - Evil or not
« Reply #2 on: October 20, 2022, 06:03:28 pm »
Context:
1) I'm not a programmer I just dabble in C and c++ to a small extent.
I have used global variables forever and have never had any issues. Am I missing something?
yes you are missing something... try to program a little bit larger. for example try to create a Windows GUI library for embedded MCU handling lots of messagings, events, interrupts etc. i recommend do it for PC where you can program larger all you like at virtually unlimited resources. at one point as your program grows and need maintenance and bugs fixes, you'll see why. this rule doesnt apply to small program. the devil is actually in yourself, it hasnt come out yet. if you can appreciate why people invented OOP (and modular subroutines much earlier) you will understand why. its quite difficult to explain to you in short sentences what an elephant is when you havent seen one.
« Last Edit: October 20, 2022, 06:08:30 pm by Mechatrommer »
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline JesterTopic starter

  • Frequent Contributor
  • **
  • Posts: 859
  • Country: ca
Re: Global variables - Evil or not
« Reply #3 on: October 20, 2022, 06:05:48 pm »
Context:
1) I'm not a programmer I just dabble in C and c++ to a small extent.
I have used global variables forever and have never had any issues. Am I missing something?
yes you are missing something... try to program a little bit larger. for example try to create a Windows GUI library for embedded MCU handling lots of messagings, events, interrupts etc. at one point as your program grows and need maintenance and bugs fixes, you'll see why. this rule doesnt apply to small program. the devil is actually in yourself, it hasnt come out yet. if you can appreciate why people invented OOP (and modular subroutines much earlier) you will understand why. its quite difficult to explain to you in short sentences what an elephant is when you havent seen one.

If you are going to quote me, please don't selectively hide the part of the quote that applies to my question.

Context:
1) I'm not a programmer I just dabble in C and c++ to a small extent.
2) Embedded application running on a smallish uC for example a small sub module in a automobile, for example: bool wipersOn = false;
« Last Edit: October 20, 2022, 06:08:18 pm by Jester »
 

Offline Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11694
  • Country: my
  • reassessing directives...
Re: Global variables - Evil or not
« Reply #4 on: October 20, 2022, 06:11:47 pm »
i dont quote what is irrelevant. or what that doesnt make any difference from the important fact that you are working on small system (or just working). so less chance for you to wander, we encountered such situation may times. but if you dont like my comment, just ask to delete it i will gladly do. you can get what you are missing (or not missing at all) from somebody else.
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Online ataradov

  • Super Contributor
  • ***
  • Posts: 11288
  • Country: us
    • Personal site
Re: Global variables - Evil or not
« Reply #5 on: October 20, 2022, 06:13:46 pm »
There is nothing wrong with use of global variables where justified. And in small embedded systems it is justified a lot.

2) Embedded application running on a smallish uC for example a small sub module in a automobile, for example: bool wipersOn = false;

In automotive environment it is a bit harder, since you will also start running into MISRA-C limitations. MISRA-C recommends to avoid global variables and make sure that the variables are declared in a scope that minimizes their visibility. But if you build your application around global variables, then global visibility becomes necessary.
Alex
 
The following users thanked this post: Buriedcode, Jester, SiliconWizard

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19635
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Global variables - Evil or not
« Reply #6 on: October 20, 2022, 06:28:58 pm »
If you are going to quote me, please don't selectively hide the part of the quote that applies to my question.

Context:
1) I'm not a programmer I just dabble in C and c++ to a small extent.
2) Embedded application running on a smallish uC for example a small sub module in a automobile, for example: bool wipersOn = false;

Such selective quoting seems to be happening more frequently on this forum at the moment. It is often accompanied by strawman arguments deployed for a variety of reasons. IMNSHO such tactics should be called out for what they are, lest too many contributors think it is acceptable.

IMNSHO the alternative is to allow conversations' value to be degraded, and hence to the degradation of the overall utility, civility and friendliness of this forum. That would be a pity.

N.B. mechatrommer's specific post snipped because I am making a more general point than that specific post.
« Last Edit: October 20, 2022, 06:30:44 pm by tggzzz »
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 
The following users thanked this post: Jester

Offline magic

  • Super Contributor
  • ***
  • Posts: 6807
  • Country: pl
Re: Global variables - Evil or not
« Reply #7 on: October 20, 2022, 06:48:25 pm »
I have used global variables forever and have never had any issues. Am I missing something?
Yes, dependency injection :D
 
The following users thanked this post: T3sl4co1l, Jester, paulca

Offline Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11694
  • Country: my
  • reassessing directives...
Re: Global variables - Evil or not
« Reply #8 on: October 20, 2022, 07:15:09 pm »
Such selective quoting seems to be happening more frequently on this forum at the moment. It is often accompanied by strawman arguments deployed for a variety of reasons.
he's asking something that is not his problem. when in small uC people talk about global variable go to hell? is like asking "people said using roger laminate pcb is better than FR4. i've been using FR4 with my small arduino fine, whats i'm missing?" and if someone posts 999 lines of irrelevant/useless statements and only one of related/usefull point of interest, should we quote/duplicate all 1000 lines of almost all useless points? where is the "doing more, with less"? ;D
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 
The following users thanked this post: WattsThat

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19635
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Global variables - Evil or not
« Reply #9 on: October 20, 2022, 07:27:06 pm »
Such selective quoting seems to be happening more frequently on this forum at the moment. It is often accompanied by strawman arguments deployed for a variety of reasons.
he's asking something that is not his problem. when in small uC people talk about global variable go to hell? is like asking "people said using roger laminate pcb is better than FR4. i've been using FR4 with my small arduino fine, whats i'm missing?" and if someone posts 999 lines of irrelevant/useless statements and only one of related/usefull point of interest, should we quote/duplicate all 1000 lines of almost all useless points? where is the "doing more, with less"? ;D

He stated accurately accurately the context which he felt should have been included.
I copied that context.
You have omitted both.
You have made a completely different point which isn't relevant to that.

You have therefore again omitted relevant context.
You have therefore again raised a strawman argument.
And that is despite my specifically stating that I was making a general point, not a specific point about your post.

Remarkable.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 
The following users thanked this post: Jester

Offline MikeK

  • Super Contributor
  • ***
  • Posts: 1314
  • Country: us
Re: Global variables - Evil or not
« Reply #10 on: October 20, 2022, 07:27:16 pm »
If you're not using that much RAM in your application there's no reason to limit your globals.  You need to avoid globals when memory use and management become an issue.  If you're fine with using globals, keep doing it until you run into problems.
 
The following users thanked this post: Jester, jpwolfe31

Offline Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11694
  • Country: my
  • reassessing directives...
Re: Global variables - Evil or not
« Reply #11 on: October 20, 2022, 07:36:37 pm »
He stated accurately accurately the context which he felt should have been included.
everybody can read his context... and here again if i want to make more into context so it can be clearer to you (i dont have to duplicate contexts that have been duplicated many times)..

The moment you google "global variable" half the comments are DON'T DO IT you will burn in hell.
you see, he have his stated context at the top, and then he claimed he googled, and found something that is weird. i highly suspect the answer he got from google are for entirely different context (or from some clueless posters). not for his specific context. prove me wrong. i gave you analogy (about Roger vs FR4 in case you missed that).
« Last Edit: October 20, 2022, 07:38:32 pm by Mechatrommer »
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14553
  • Country: fr
Re: Global variables - Evil or not
« Reply #12 on: October 20, 2022, 08:09:14 pm »
As with anything else, the crux of the matter is not whether you should or should not use them, but why, how and when.

Since "DON'T DO IT you will burn in hell." doesn't answer any of that, you guessed it right, it's useless.

To start the thought process, you must begin with the distinction between declaring globals for the static allocation of state data and *accessing* globals directly in functions without passing them around as parameter. The two are orthogonal, yet many, especially beginners, will confuse the two in nice chunks of spaghetti code.

- For the former, one way or another you will have to use global variables, unless you are OK with using dynamic allocation on the heap (which is usually not a good idea at all on small MCUs) or maybe even on the stack (for instance, if you allocate local variables in your main() function to store global state, why not - it may just unnecessarily eat up stack space which is usually very limited on small MCUs.)

- For the latter, you can absolutely use global variables while limiting a direct access to them to the very bare minimum and otherwise passing them as parameters to functions, or pointers to them. This is by far the preferred way of doing it unless you like spaghetti. (It's good as a dish, not so much for software.) Doing that will tremendously help 1/ maintaining code and making it scalable, 2/ verify and validate code.
 
The following users thanked this post: Jester

Offline AndyBeez

  • Frequent Contributor
  • **
  • Posts: 856
  • Country: nu
Re: Global variables - Evil or not
« Reply #13 on: October 20, 2022, 08:12:22 pm »
For 'production' programming - in any language - you should be thinking about keeping your variables in some kind of Data Structure. A data structure acts like a master collection of variables with global scope.

Defined either as an array, or a class with getter and setter methods, a data structure is a means of storing values so they can be used by the run time, but keep them together in their own memory bear pit. 

In your example, the wiper control function might access Vehicle.Wippers.Speed or Vehicle.Wippers.Clean. The lighting control function uses Vehicle.CabLight.Mode. But every value is inside the Vehicle global class. Whether these individual values are Booleans, Strings, Numerics, Enumerations - or even whole functions - that's up to you.

For code maintenance, holding values in an organised data structure, rather than a splurge of local and global scopes variables referenced by *&pointers, makes for adding and subtracting values a lot less than evil >:D

 
The following users thanked this post: Jester

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19635
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Global variables - Evil or not
« Reply #14 on: October 20, 2022, 08:29:01 pm »
He stated accurately accurately the context which he felt should have been included.
everybody can read his context... and here again if i want to make more into context so it can be clearer to you (i dont have to duplicate contexts that have been duplicated many times)..

... and there you go again.

'Nuff said.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 
The following users thanked this post: Jester

Online RoGeorge

  • Super Contributor
  • ***
  • Posts: 6269
  • Country: ro
Re: Global variables - Evil or not
« Reply #15 on: October 20, 2022, 08:33:29 pm »
Am I missing something?

Yes, but not about programming, it's something else much deeper:
There is no such thing as (standalone) Good or Evil.

These concepts of Good and Evil only makes sense in relation to a goal.  What helps with the given goal is considered Good, what stands against is Evil.  What is Good for one can be Evil for other.

About global variables, if they help your code, they are Good, if they create problems, they are Evil.

Sometimes they are considered bad practice because people often forget about them, or are not told about them (in bigger projects) so they reuse that variable name, and thus they create a mess hard to debug.

In embedded programming, where each byte and each clock cycle counts, and where the stack memory is usually very small, the tale about global variable is quite contrary:  Global variables are preferred, because they can make the code shorter and faster.
« Last Edit: October 20, 2022, 08:38:39 pm by RoGeorge »
 
The following users thanked this post: Jester

Offline coppice

  • Super Contributor
  • ***
  • Posts: 8706
  • Country: gb
Re: Global variables - Evil or not
« Reply #16 on: October 20, 2022, 08:36:27 pm »
Global variables easily become a religious issue, like many programming topics. There is nothing fundamentally wrong with global variables. Some things really are truly global, and there is no point in treating them any other way. Things you initialise at startup, and will never change during the runtime of the program, have no reason to be treated as anything but global variables. The problems come not from their use, but their overuse.
 
The following users thanked this post: Jester

Offline langwadt

  • Super Contributor
  • ***
  • Posts: 4459
  • Country: dk
Re: Global variables - Evil or not
« Reply #17 on: October 20, 2022, 08:45:34 pm »
Global variables easily become a religious issue, like many programming topics. There is nothing fundamentally wrong with global variables. Some things really are truly global, and there is no point in treating them any other way. Things you initialise at startup, and will never change during the runtime of the program, have no reason to be treated as anything but global variables. The problems come not from their use, but their overuse.

yeh, all the IO and peripheral registers are global ..
 
The following users thanked this post: Jester

Offline CatalinaWOW

  • Super Contributor
  • ***
  • Posts: 5263
  • Country: us
Re: Global variables - Evil or not
« Reply #18 on: October 20, 2022, 10:43:11 pm »
A simple example shows how many rabbit holes this question can dive into.  Take one of the physical constants.  Pi.  Seems like a perfect candidate for a global level.  There are languages in which is made available as a language define value.  There shouldn't be any issues with someone writing while someone else is reading.

But dig a little deeper.  Some parts of your application may need full double precision or greater.  Others want want less for speed or memory efficiency, or even just to assure consistency with another source.  I have even seen applications where using integers and the 22/7 approximation makes sense.  If any or all of these happen the benefit of global application diminishes and may go negative.

 
The following users thanked this post: Jester

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4050
  • Country: nz
Re: Global variables - Evil or not
« Reply #19 on: October 20, 2022, 10:57:26 pm »
Context:
1) I'm not a programmer I just dabble in C and c++ to a small extent.
2) Embedded application running on a smallish uC for example a small sub module in a automobile, for example: bool wipersOn = false;

I appreciate a global variable in some large program for some large company for example American Airlines would probably be a really bad idea.

The moment you google "global variable" half the comments are DON'T DO IT you will burn in hell.

I have used global variables forever and have never had any issues. Am I missing something?

There are two different issues:

1) static lifetime for a variable. This is absolutely necessary for statefull programming. Sometimes these variables may even need to be in EEPROM rather than RAM so they survive reset/power off.

2) too much visibility of a static variable, such that you can't easily know which parts of the program read and/or write to it.

Tools such as an IDE or even simply grep on the command line can help you find all the places a variable is used.

If a variable is used in a single function then it can be declared as "static" inside that function.

If a variable is used in a small number of functions then it and those functions can be gathered in a single C file and the variable global in that file but  marked as static. Other C files will then not be able to refer to it by accident.


In a small program none of this is a problem. The potential problems arise in large programs with poor modularity discipline.
 
The following users thanked this post: Buriedcode, Jester

Online T3sl4co1l

  • Super Contributor
  • ***
  • Posts: 21734
  • Country: us
  • Expert, Analog Electronics, PCB Layout, EMC
    • Seven Transistor Labs
Re: Global variables - Evil or not
« Reply #20 on: October 20, 2022, 11:25:10 pm »
0. It doesn't matter, everything goes, it's C, do whatever you like!

1. Who are you really writing for?

If for the machine, do whatever you like.

If for other programmers -- give some consideration to what they will find understandable.

This includes your own future self!  An issue you may've noticed already, or maybe not if you're still fairly new to this, or just very consistent in your writing style.  (Which could kinda mean two things: that you're very consistent and familiar with your own dialect (or many dialects), or that you indeed format and comment things well already.  Preferably, the former is the latter. :) )

2. What is the purpose of this issue?

Globals are readable and writable by any module in the system, whether they "should" be able to or not.  Mind, that means semantically: C of course doesn't give a shit if you trample random memory, that's your own prerogative.  It's about visibility and scoping, and how much interface is exposed between modules.

Note that, depending on compiler version and declarations, globals may be automatically shared, or not.  In GCC < 8 I believe?, they were shared; after, not.  Scope can be controlled by prefixing static (local to module) or extern (shared).

The temptation is that, with globals shared and scoped, they become part of the interface, whether intended or not, and complexity grows massively.  Every outside reference to a variable, is one more reference you need to keep track of, with respect to state changes within the module (if indeed the variables declared within it are mostly/entirely used locally -- you don't have to, of course..!), the consistency thereof, and what ways the module can be interacted with.

Ultimately, what this drives towards is the matter of reusability, that a module should be largely self-contained, expose only its documented interfaces, and enforce that as such.

A recent example I used is this,
https://github.com/cwalter-at/freemodbus/tree/master/modbus
It's fairly old and mature, actively maintained (well, there are a couple PRs sitting around for a few years, but last I looked, all quite minor and easily implemented yourself), and very modular.  You implement the physical/interface bits in the port files, implement the callbacks (messages translated into read/write commands, you implement the read/writing yourself), pick the interface you want (on init), then poll in a main() loop.  The code is fairly compact, straightforward -- Modbus is a pretty thin and simple stack, but a stack it is -- and easy enough to understand.  So, I think it's a good illustration of how convenient this style of design and organization is.

Which leads into:

3. https://en.wikipedia.org/wiki/Dependency_injection

As mentioned above, it's another design pattern that can help simplify things.

The apparent downside for embedded purposes is, all this boilerplate doesn't matter, you're only ever going to use one configuration, and you're checking memory regularly (well, maybe) and it's all flat in the end, who cares.

Well, the overhead is small; in C, the function pointers used during MBinit() for example, will always emit a load, call (register indirect) operation (or, I think so, anyway?).  Distinctly slower than absolute call, let alone inlining the thing whole.  But how often are you calling MBinit()? Just once?  Yeah who cares about an extra five or 20 cycles.  And the polling is done, whatever, say every millisecond, what's another couple dozen cycles on that, who cares?

The worst part is probably interrupts, which are often written as callbacks in these sorts of things (see also: STM32 HAL and the like), so all registers on the ABI's clobber list must be saved and restored around the call.  But here still, it needn't be a problem.  For Modbus at least, conventional baud rates are slow (9600, 19200...) so few interrupts can fire per second.  YMMV for whatever kind of module, of course, but the point is, many things aren't performance sensitive, or nearly as much as you're apt to think in the embedded world.

In C++, more of these are likely to be optimized down, AFAIK, so, a constant function pointer at compile-time may end up inlined, say.  In that case, there's literally no downside.

Exposure to newer languages probably helps out as well.  Being familiar with say Java Objects (everything is an Object, no pointers, only references), or lambdas or other functional things (Factory design pattern; passing functions as parameters or objects; etc.), gives you a higher level perspective that you'd never realize deep down in the trenches of plain C.  Even if you're never using the full form of those structures, knowing that they're there, and that you could express what you're doing as a reduced form of one of these constructs -- can help organizing things.

Tim
Seven Transistor Labs, LLC
Electronic design, from concept to prototype.
Bringing a project to life?  Send me a message!
 
The following users thanked this post: Jester

Offline Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11694
  • Country: my
  • reassessing directives...
Re: Global variables - Evil or not
« Reply #21 on: October 20, 2022, 11:26:14 pm »
there are enough materials in the net to educate about the why not to use them (on certain programming scale/topology/hierarchy/concept/design) this is more "theoretical" or "logical" rather than trivial matter such as to save memory space or make things faster to run etc, certainly not in the context of OP. if you happened to buy an academic books about teaching you into larger scale software/data design/structure, you will sometime see this hinted by the author who happened to be a professor or at the same level as people like Mr Bjarne. those who have been bitten know how to appreciate and know this is something for real albeit intangible with no physical appearance, those who have a hard time understanding the why, that means its none of their business, they can do whatever they like and certainly nothing will go wrong... i bet their software is simple enough to maintain no matter how complex they think it might be...

https://www.tutorialspoint.com/Why-should-we-avoid-using-global-variables-in-C-Cplusplus


Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 
The following users thanked this post: Jester

Offline mac.6

  • Regular Contributor
  • *
  • Posts: 225
  • Country: fr
Re: Global variables - Evil or not
« Reply #22 on: October 22, 2022, 08:13:19 am »
In embedded system, especially constrained ones, global variable are mostly required.
But what matters is how you use them.

Direct access to global variable is the culprit. this is the start of the spaghetti code, all your code is tied by the globals references.

So better use a global pointer/structure for one or more global context, then a bunch of accessor function.
This way you can easilly control access and reuse your code.

All the fuss about visibility/abstraction only matters if you share code or doing libraries. If you controll 100% of your code and partition it correctly it doesn't matter at all.
 

Offline Siwastaja

  • Super Contributor
  • ***
  • Posts: 8186
  • Country: fi
Re: Global variables - Evil or not
« Reply #23 on: October 22, 2022, 09:14:59 am »
Terminology:

NOT global, but file-scope static variable:

Code: [Select]
file.c:
static int var; // accessible to all functions in file.c

Actual global:
Code: [Select]
file.h:
extern int var; // include file.h to access var from any module

file.c:
int var;

You can also say var is now part of the interface of this module.


File-scope statics can't be realistically avoided in C, they store shared state between the module functions. Equivalent to private member variables in C++ class.

Actual globals can, and maybe should be avoided, but sometimes they are just the easiest way and they don't magically transform your code into shit. If you find yourself using globals all the time, you can ask yourself if you could abstract the functionality better so that, for example, uart.c does all UART-related things and interface only consists of a few functions, not variables.
« Last Edit: October 22, 2022, 09:17:05 am by Siwastaja »
 

Online ejeffrey

  • Super Contributor
  • ***
  • Posts: 3734
  • Country: us
Re: Global variables - Evil or not
« Reply #24 on: October 22, 2022, 05:51:34 pm »
There are a couple of problems with global variables, how big of a problem they are depend on your situation.

The first is name collisions and is really specific to C which has no good namespace support.  Almost any other language in common use has either default or optional module level namespaces.  This allows you to make a module variable visible globally but require it to be qualified by a module name when uses in other modules.  The standard way to avoid this in C is to use prefixes which works OK.  If you are going to use globals in anything reusable or more than a handful of .c files in a single directory I strongly recommend doing this.

The second is that you lose control over how a variable is used.  For instance if you want to make a project thread safe, you might need to add locks.  If you have accessors you have a way to do this that is much simpler than if you have to change every access.  Global variables can also have issues with order of initialization. If a global variable has complex initialization it can be difficult to ensure that it is initialized before access.  Dedicated accessor functions that check for and perform initialization can't completely solve this problem but at least give you a hook to solve it.

The above two problems are with the implementation of global variables.  The third problem is more with the concept of global state which is that global variables are basically by definition singletons.  There are a lot of instances where "global" state turns out to not be global.  GUI frameworks are notorious for this, treating the GUI handle and the event loop as global singletons.  This is undeniably convenient as you avoid passing context objects around in every part of your code.  It's particularly convenient in callback heavy code as it is one less but of context you have to figure out how to get back to your callback in a language with no native support for nested functions or closures.  But embedded applications are not immune to this, often treating things like "the" serial/console port as a global.  If a future implementation requires multiple IO devices can result in a lot of code that needs to be rewritten.

So not evil but something you should think about, and there are good reasons why some environments heavily restrict them.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf