Static local variables in methods a bad practice?

there is something that's bugging me.

In a non-threaded program, is it better to have local static variables(inside methods) or static class members?

In this example:

class C{
public: 
  C(){};
  void foo();
};

void C::foo(){
  static int bar = 0;
  bar++;
  printf("%d\n",bar);
}

Is it considered a bad practice if bar will solely be used in C::foo()?

Answers


Neither is better. They serve very different use cases


I usually try to limit the scope of variables as much as possible, as long as it doesn't become weird or tedious.

If you have 1000 lines of code in class C, of them 100 lines of code in the function foo, any change you do to bar (for example, changing the name or type) requires going over 100 lines of code to make sure the change is OK. If you had bar a static class member, you might have to go over 1000 lines of code, just to make sure bar is not used there. This would be a waste of time.

If you think you might need bar in another function foo2 (for example, when counting call count for foo and foo2 together), you might want to make bar a static class member.


If it's a public class, a static class member requires editing the header file. This is not always desirable.

Another option is a file-scoped variable, in an anonymous namespace. This is sufficient if you need access only in one method, and if you need it in multiple.


Both local and non-local global variables are "bad" by the virtue of being global. But initialization and access for those two cases are different, so the answer which one to use depends on your needs regarding those requirements.

As a side note, dynamic initialization of local variables with static storage duration may not be thread-safe, depending on your compiler. The good news, in C++0x it's guaranteed to be thread-safe.


Object-oriented-speaking, bar is part of the state of class C. This is the reason why I usually prefer using fields rather than static local variables.


Need Your Help

Unexpected behavior with overloaded methods

groovy

I'm a bit confused about groovys method overloading behavior: Given the class

':' character in JasperReports HTML output

encoding jasper-reports

I am working with JasperReports with HTML as the export format. The problem is that from my Java class, I set the parameter with a String value containing the ':' character, when I click the button...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.