Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
I am sure if this question programmers.stackexchange.com/questions/47923/… counts as a duplicate, but it may help you. –  Doc Brown Dec 29 '13 at 22:48
    
Yeah that is kind of similar but I think it is more related to object orientated applications. –  stmfunk Dec 29 '13 at 23:17
1  
it seems you are trying to decide between a extra parameter and a global... –  ratchet freak Dec 30 '13 at 0:11

2 Answers 2

up vote 5 down vote accepted

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
share|improve this answer

Right now I can't see a reason why you should use a global variable instead of passing another parameter around except in the case where you're dealing with performance-critical code and you might have constraints like stack memory, ABI restrictions and such.

This applies to the C code you asked in the question, wouldn't totally fit in an object oriented context (although people also use C++ objects in performance-intensive contexts).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.