Short answer: no, it is not a good practice to move a variable out of functions just because it is "repeating".
Once you learn the syntax of a language and move beyond tiny little demonstration programs, much of the task of computer programming becomes one of managing complexity. And one of the most important tools for managing complexity is modularity, of keeping things localized.
So for that reason alone, and as a general rule, local variables are a very good thing, and global variables are usually a bad thing. You use global variables only when you really have to, when their use carries a clear benefit, when there's no good way to achieve your task some other way.
In this case, if you have two different local variables in two different functions, but that do more or less the same thing, it is truly: no problem at all. Precisely the same argument would apply to, for example, local variables named i
that are used as loop counters.
It sometimes seems like there's an impetus to keep things "tidy". And I can see how declaring one FILE *fp
up at the top of the source file, rather than redundantly in each function, might seem "tidier". But in practice, that kind of "tidiness" buys you nothing.
A related example concerns declaring multiple variables on the same line. Some programmers believe (or are taught) that they should declare a lot of variables together, grouped by type:
int i, number_of_whales;
double ocean_depth, water_density, temperature_in_tokyo;
float whale_weights[100];
But this organization, while it might look nice and "tidy", ends up serving no practical purpose, and can even be a practical impediment. The compiler doesn't care how you declare your variables. But you and other people reading your program do, so the question is, what makes things easier for them? And the answer is that you want to declare your variables in some useful order: either alphabetically, or grouped by related use, or in the same order as they're used. But grouping them together by type doesn't make anything easier for anybody. (I realize this isn't the question you asked, but it makes the same point: we don't care about what looks tidy, or what seems tidy, what we actually care about is what makes our program easier to understand and to manage.)
The other thing to remember about global variables is that they are, well, global. What would happen if, as your program grows and improves and adds features, the insertline
function ended up calling some other function which called some other function which called deleteline
? If deleteline
shared a global fp
variable with insertline
, then by the time control flow returned back to insertline
, its fp
would be messed up. (This isn't a terribly good example, because it's hard to imagine insertline
ever calling down to deleteline
, and if it did, there would probably be other problems. But I hope you see my point.)