Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Pointers and Global Variables in C?

I'm reading The C Book to try and get a better foundation in C. While I think I'm generally getting the concept of pointers, one thing sticks out to me is that it seems like it's generalizing whatever it's pointing to into a global variable (e.g. the ability to use pointers to return values from void functions), which naturally carries with it all the attendant dangers, I assume.

Aside from the fact that a pointer references a specific variable or index in an array, what is the difference between a pointer and a global variable?

like image 799
Kaji Avatar asked Dec 12 '09 03:12

Kaji


1 Answers

There's a huge difference. Aside from the "other" uses of pointers (which include dealing with strings and arrays, and building dynamic data structures like trees and linked lists), using a pointer to give another function access to a local variable is much more flexible and controlled than sharing a global variable between these two functions.

Firstly, it allows the called function to be provided access to different variables at different times. Think how much more laborious it would be to use scanf() if it always saved its results into the same global variables.

Secondly, passing a pointer to another function makes you much more aware of the fact that that function will be able to modify the object. If you use a global variable for the same purpose, it is easy to forget which functions modify the global and which do not.

Thirdly, global variables consume memory for the life of your program. Local variables are released when their containing function ends, and dynamically-allocated data is released when it is freed. So global variables can at times be a considerable waste of memory.

Using pointers leads to the danger of referring to variables that no longer exist, so care has to be taken. But this is most often a problem when there are complicated global or long-lived data structures which in itself is often a design weakness.

Globals just get in the way of good, modular program design and pointers often provide a better way to achieve the same things.

like image 65
Artelius Avatar answered Oct 06 '22 09:10

Artelius