Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid globals in C?

Tags:

c

global

As a beginner, I read everywhere to avoid excess use of global variables. Well how to do so? My low skill fails. I am ending up passing tons of structures and it is harder to read than using globals. An tips on going through this problem/application structure design?

like image 636
dummyprogrammer Avatar asked Dec 28 '22 09:12

dummyprogrammer


1 Answers

Depending on what your variables are doing, global scope might be the best scope. (Think flags to signal that an interrupt has arrived, and should be handled at a convenient time in the middle of a compute loop.)

Small utility programs can often feel much cleaner by using global variables (I'm thinking especially of small language parsers); but this makes it much harder to integrate the small utility programs into larger programs in the future. There are always trade-offs.

But chances are good the "correct" data organization will not feel quite so cumbersome. If you post code here, someone may be able to suggest cleaner layout, but the real problems come when code grows beyond easily-understood small samples.

I have a LOT of favorite programming style books, but I think the best I know of to address this situation is The Elements of Programming Style, by Kernighan and Plauger. It's quite old, and difficult to find, but short, sweet, and well worth finding used somewhere.

It's not as short, it's not as sweet, but still well worth finding Code Complete, 2nd edition. It's much more detailed, provides much more code, and provides much more diversity involved in designing software. It's excellent, but might be more intimidating.

There's nothing like studying the masters: the code in Advanced Programming in the Unix Environment, 2nd Edition is phenomenal, well worth every hour of study.

And, of course, there's always experience, but that takes time to acquire. Learning lessons from your own mistakes tends to stick much stronger than learning lessons from other people's mistakes. So keep at it. :)

like image 100
sarnold Avatar answered Jan 11 '23 19:01

sarnold