[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [MiNT] Programming style



Jo Even Skarstein wrote :
must I move the local static variable out of the function, or is this OK?

Global variables are bad, because the cause reentrency problems.

Static global variables are a bit less bad, because they are local to a single C file and can't be used by error from other sources.

Static variables defined inside functions are again a bit less bad, because they are accessible only inside their function. However they are still hidden global variables, and the reentrency problems are still here.

Static variables defined inside functions have an additional, less known feature. They are initialized on the first function call. So at the start of any function containing initialized static variables, there is a hidden code like this:

if (!static_variables_initialized)
{
  /* Initialize static variables */
  static_variables_initialized = 1;
}

So because of this test, functions using initialized static local variables are a bit slower as those using global variables. It just involves an additional if(), so the difference is usually unnoticeable.

I made some tests about this feature long ago, I hope it is still valid when using current compilers.

Personally, when I absolutely need some kind of global variable, I prefer using a static variable inside a function, the source is cleaner.

--
Vincent Rivière