Reputation: 13
Here is an example code, struct A is declared and then it's instance "instanceOfA" is defined inside main, so it become local variable and to access it in other functions I should pass it as an argument. On the other hand struct B is declared and it's instance defined as global variable that allows me to use "instanceOfB" anywhere I need it, directly instead of passing it around as an argument. The only thing I should worry about now is that some function may overwrite "instanceOfA" identifier right? since it's variables (a,b,c) already in it's own "namespace". So is it a bad practice to define struct object as global variable? What would you do? Sorry for my poor English.
struct A {
int a,b,c;
};
struct B {
int a,b,c;
} instanceOfB;
int main(void) {
struct A instanceOfA;
instanceOfA.a = 5;
instanceOfB.a = 10;
}
Upvotes: 0
Views: 2884
Reputation: 61993
Yes, indeed, it is very bad practice to define anything as a global variable, not just a struct.
Yes, you will need to be passing it as a parameter. That's actually good, not bad.
It means that every single individual piece of code (function) in your program will only be able to modify what it is being given to modify, and not whatever it pleases.
Upvotes: 1
Reputation: 13003
I'm not sure what is the question about exactly, but here are some thoughts.
instanceOfB
is a global variable, right? So, it is an evil that should be avoided if not strictly necessary.
On the contrary, struct A instanceOfA;
inside function body looks fine for me, though we usually move types from struct
namespace to global namespace by using typedef struct
idiom to reduce typing.
Upvotes: 1