Search code examples
cpointersglobal-variables

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?


Solution

  • They're quite different beasts. To better explain, let me define both.

    Pointers:

    A variable holds some piece of data. A pointer is a type of data that refers to another piece of memory. Think of it as a sign that says "Over there ---->" pointing at an object of some sort. For example, strings in C are just a pointer to a character, and by convention, you know there's more characters following it until a \0 character. C uses pointers extensively, since there's no other mechanism for sharing common information between parts of the program, except for....

    Global Variables:

    In a program, you have variables in each function. These can be the parameters to the function, and ones defined inside. As well, you have what are known as global variables. These variables store information that all the functions in a file can access. This can be useful to pass things like a global state around, or configuration. For example, you might have one called debug that your code checks before printing some messages, or to store a global state object, like the score in a video game.

    What I think is confusing you: Both can be used to share information between parts of code. Because function arguments are passed by value in C, a function can't modify the variables of what calls it. There are two ways to "fix" that problem. The first (and correct) way is to pass a pointer to the variable into the function. That way, the function knows where to modify the parent's variable. Another approach is to just use a global variable. That way, instead of passing around pointers, they just edit the global variables directly.

    So you can use both of them to accomplish the same thing, but how they work is quite seperate. In fact, a global variable can be a pointer.