Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 976
Manux Avatar asked Dec 29 '10 17:12

Manux


People also ask

Are static local variables bad?

Are static local variables bad practice? No. Static local variables differ in exactly one regard to non-local private variables: they have a smaller scope. Since you always want to keep scope as small as possible (= better encapsulation), local statics can be advantageous over private variables.

Is it bad practice to use static methods?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.

Are local variables in static method thread safe?

Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.

What would happen if we declared a local variable as static local?

When applied to a local variable, the static keyword defines the local variable as having static duration, meaning the variable will only be created once, and will not be destroyed until the end of the program.


1 Answers

Neither is better. They serve very different use cases

like image 89
Falmarri Avatar answered Sep 28 '22 10:09

Falmarri