Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>Firstly, it allows the called function to be provided access to <em>different</em> variables at different times. Think how much more laborious it would be to use <code>scanf()</code> if it always saved its results into the same global variables.</p> <p>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.</p> <p>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 <code>free</code>d. So global variables can at times be a considerable waste of memory.</p> <p>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.</p> <p>Globals just get in the way of good, modular program design and pointers often provide a better way to achieve the same things.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload