C Programming – External Variable vs Pointer

cpointers

While writing in C, I have always wondered about when is the best time to use an external variable. I generally prefer to pass a pointer into a method. Is there a correct time to use an external variable and a correct time to use pointers?

Best Answer

Variables should always have the smallest scope possible. This may lead to the "annoyance" of not being able to access the variables easily, but that is actually the point! The more you hide a variable from intrusion the better. If you can keep a variable safe from all reading and writing except from one point, that is the best! This aids in writing bug-free code.

So to answer your question more specifically, pass variables as follows with #1 being the best method:

  1. By value
  2. As a pointer to variables where the address and data are constant
  3. As a pointer to variables where the address and data are not constant
  4. Globally to one file only
  5. Globally to all files