Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to avoid global variables in a strictly procedural program?

Tags:

c

Being a developer born and raised on OO, I was curious to hear how it's possible to avoid global state in a procedural program.

like image 437
Pierreten Avatar asked Apr 29 '10 15:04

Pierreten


3 Answers

You can also write object-oriented code in C. You don't get all the C++ goodies and it's ugly, and you have to manually pass the this pointer (I've seen self used for this, in order to make it compatible with C++), but it works. So technically, you don't need global state in pure procedural languages for the very same reasons you don't need it in object-oriented languages. You just have to pass the state around explicitly, rather than implicitly like in OO languages.

like image 139
OregonGhost Avatar answered Sep 28 '22 05:09

OregonGhost


As an example, look at how the file I/O functions in the C standard library work with pointer to FILE objects that are (largely) opaque. Or look at how OS APIs deal with handles and such to encapsulate information. A program creates objects, uses APIs that act on those objects and closes/deletes the objects - all using straight C.

like image 20
Michael Burr Avatar answered Sep 28 '22 07:09

Michael Burr


A global variable is nothing but an implicit procedure argument. Make it explicit and the global variable goes away.

Note: the fact that you no longer use a global variable does not mean that you no longer use global state! What we did above was just a purely syntactical transformation, the semantics of the program haven't changed at all. It's just as non-composable, non-modular, non-threadsafe, non-parallelizable as it was before.

like image 42
Jörg W Mittag Avatar answered Sep 28 '22 05:09

Jörg W Mittag