On 12/27/2010 8:57 PM, Mark wrote:
> I'm working with a code (not mine) on embedded MIPS platform and ran
> across a weird behavior. I have a function:
>
> int nvram_init(void *si)
> {
> static int nvram_status = -1;
> ...
> }
>
> This function gets called only at one place of the firmware, what really
> strange is that output value of 'nvram_status' at the very beginning of
> the 'nvram_init()' is always 0.
How do you know this? (See below.)
> As per my knowledge, a variable declared 'static' withing a function's
> body must maintain it value between the function's calls, but it doesn't
> seem to be the case here! Should I be looking for some hardware/compiler
> specific trick, or I'm missing something more trivial?
Yes, a `static' variable retains its last-stored[*] value from
one function call to the next, or more generally from one assignment
to the next. If there has been no assignment, the `static' variable
holds it initialization value, or "the right kind of zero" if there
is no initializer. Based on what you've shown, `nvram_status' should
have the value minus one the first time nvram_init() is called. I
therefore suspect that you have not shown everything that's relevant.
In particular, you haven't shown how you determine the original value
of `nvram_status' -- and it's possible that the determination itself
might be at fault.
[*] For a `volatile' variable, "last-stored" might not be a visible
action of the program: a hardware clock or some such might "store" a
new value in the variable without an explicit assignment by the program.
However, `nvram_status' is not `volatile', so we need not consider that
potential complication.
--
Eric Sosman
lid