It's not just about preserving the value. Sometimes it's about stack space.
Here's the trade-offs for static variables within a function:
Advantages of static variables within a function (compared to non-static
variables, also within a function):
-----------------------------------
* Doesn't use any of the scarce kernel stack space
* Preserves values (not always necessarily and advantage)
Disadvantages:
-----------------------------------
* Removes basic thread safety: multiple threads can no longer independently
call the function without getting interaction, and generally that means
data corruption.
So here, I suspect that the original motivation was probably to conserve stack
space, and the author likely observed that there was no concurrency to worry
about: the function was only being called by one thread at a time. Given those
constraints (which I haven't confirmed just yet, btw), a static function variable
fits well.
My suggestion is to remove the static and define it {0} instead of memset
every time. Is my understanding correct here?
Not completely:
a) First of all, "instead of memset every time" is a misconception, because
there is still a memset happening every time with {0}. It's just that the
compiler silently writes that code for you, and you don't see it on the
screen. But it's still there.
b) Switching away from a static to an on-stack variable requires that you first
verify that stack space is not an issue. Or, if you determine that this
function needs the per-thread isolation that a non-static variable provides,
then you can switch to either an on-stack variable, or a *alloc() function.
I think you get some point. While one more question about stack and static. If
one function is thread safe, which factor determines whether we choose on
stack value or static? Any reference size? It looks currently we don't have a
guide line for this.