Global variables are generally considered to be a poor programming practice
In C, are static variables (i.e with module (file) scope) considered OK?
My thought was that member variables in an object oriented language cannot be much less dangerous than static variables in C and member variables seem to be considered to be a good thing.
I'm tiring of passing parameters through multiple functions and can see the attraction of static variables for this, especially if they are const
.
But I'm keen to know if this is frowned upon - and also whether there is really any difference in level of programming naughtiness between a big object with a member variable used in several of its methods and a C file containing a few functions that utilize a static variable?
Static (file-scope) variables in C are similar to static member variables in C++.
Any use of non-const static variables for communicating between functions makes those functions nonreentrant and thread-unsafe. Thus, in general it would be preferable to pass the information via parameters.
A better analogue for non-static member variables is a struct member. Just collect your "member variables" in a struct and pass that struct as a "this" parameter.
The big difference is: with member variables you can have multiple objects and each has its own member variable. With module scope static variables you have exactly one instance of the variable.
If you want to compare module level static variables and static class member variables then there is no real big difference. Both are instantiated exactly once, only the scope and access rules are different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With