Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice in use of static variables in C [closed]

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?

like image 947
bph Avatar asked Nov 11 '11 14:11

bph


2 Answers

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.

like image 150
ibid Avatar answered Sep 27 '22 19:09

ibid


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.

like image 22
Werner Henze Avatar answered Sep 27 '22 18:09

Werner Henze