0

My situation is this:

  • a header aux_func.h with prototype of a function int check_format_file(FILE * file);
  • a source file aux_func.c with implementation of that funcion

The question is: In my main.c, where and how is better to declare FILE * f ?

  1. As a static global variable

#include aux_func.h

static FILE * f;

int main() 
 {
    check_format_file(f);  
  /* other stuffs */  
  return 0;  
 }
  1. As an istance variable declare in main ?
#include aux_func.h

int main() 
 {
  FILE * f;
  check_format_file(f);  
  /* other stuffs */  
  return 0;  
 }

My doubt is about the correct visibility of FILE *f.

Kyrol
  • 3,475
  • 7
  • 34
  • 46

2 Answers2

2

In both the cases, you are passing f to the one and only function check_format_file(), so there is no need to make it static and global. Nobody is going to alter the value of f (I hope so, because if somebody is going to modify it, then you have many more worries than this) and the way you are passing it to the other function, makes sure that it will be visible to the function.

From SO Question,

Variables should always have the smaller scope possible. The argument behind that is that every time you increase the scope you have more code that potentially modifies the variable, thus more complexity is induced in the solution.

It is thus clear that avoiding using global variables is preferred if the design and implementation naturally allows that. Due to this I prefer not using global variables unless they are really needed.

Community
  • 1
  • 1
Abhineet
  • 5,320
  • 1
  • 25
  • 43
  • actually, `f` is also passed to another function in main, that is defined in an another `.h`, different from `aux_func.h`. Are there any differences in this case or not? – Kyrol Dec 10 '13 at 14:29
  • As long as you are passing it. No, there is no difference. It will work. – Abhineet Dec 10 '13 at 14:31
0

I would go with the second option because it seems that you are not going to use the variable f out of this function that's why there is no reason to make it global.

Rufi
  • 2,529
  • 1
  • 20
  • 41