Alex Rivera | Logout

Static local variables in methods a bad practice?

Asked 2010-12-29T17:49:46.273
10

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()?

Edit
Report

2 Answers

7

Neither is better. They serve very different use cases

answered 2010-12-29T17:52:23.377
0

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.

answered 2010-12-29T18:07:43.433

Your Answer