0

I have seen an example where someone has passed an extern struct to a function in C. Is there a good reason to do this instead of using the extern struct without passing it as a parameter? Is this solution more encapsulated?

//Test.h
struct TEST_STRUCT
{
    int   member;                                                 
};
extern struct TEST_STRUCT test_struct; 

//Test.c
struct TEST_STRUCT test_struct = {0};   

Now I can decide to pass this test_struct to my function or to set my "member" variable in my function very comfortable like this:

test_struct.member = 10;
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • What do you ask? There is no function shown. What don't you understand in your favorite C book? Or any online-tutorial? What else did you find out yourself you dont fully understand? – too honest for this site Aug 12 '16 at 16:58
  • What do you mean? What do you call `passing`? There are no function calls in your code – qrdl Aug 12 '16 at 16:59

1 Answers1

0

It is generally better to avoid global variables and to pass the information needed by a function to that function using parameters rather than relying on global variables. All else apart, you can only have one global variable; you may have many functions that need to call the one function with different values at different times. However, it is hard to tell whether another function is relying on the current value of the global variable.

So, yes, passing (a pointer to) the structure explicitly is generally better referencing the global variable — it encapsulates the information better.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278