I have a global var struct:
typedef struct {
int myvar1;
int myvar2;
int myvar3;
...
int myvar10;
} t_myStruct myGlobalData;
I cannot avoid this global structures, so I have to use it.
I have three options to use it:
-
Use the global var “as is” into any function. I.e.:
int myFunc(void) { myGlobalData.myvar1 = ... myGlobalData.myvar10 = myGlobalData.myvar5 + ... } -
Declare a local pointer and use it:
int myFunc(void) { t_myStruct * p; p = &myGlobalData; p->myvar1 = ... ... p->myvar10 = p->myvar5 + ... } -
Use local var and then copy to global struct:
int myFunc(void) { t_myStruct localStruct; localStruct.myvar1 = ... localStruct.myvar10 = localStruct.myvar5 + ... myGlobalData = localStruct ; }
Could explain me what is best way in general and why?
Choose more abstraction. If you can change the arguments to
myFunc, then make its signature:Now the function itself doesn’t depend on the existence of a global variable at all. And the same for any other functions that need to operate on a
structof this type. If you must use a global variable then isolate the use of it as much as possible, i.e. use the global in as few places as possible.If you can’t change the function signature, I would choose the option from your question that is the most direct: the first. Just operate directly on the global variable.