A colleague is doing some code review, and he is seeing many static variable declarations similar to the following:
void someFunc(){
static int foo;
static int bar;
static int baz;
foo = 0;
bar = 0;
baz = 0;
/*
rest of the function code goes here
*/
}
Our question is, Are the programmers who wrote this code simply unclear on the concept of a static variable, or is there some clever reason to do this on purpose?
If it makes any difference, the environment is an embedded microcontroller and the compiler is GCC.
1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over. For example, we can use static int to count a number of times a function is called, but an auto variable can't be used for this purpose.
static. The static keyword can be used to declare variables and functions at global scope, namespace scope, and class scope. Static variables can also be declared at local scope. Static duration means that the object or variable is allocated when the program starts and is deallocated when the program ends.
One good use for a const static local variable is when you have a function that needs to use a const value, but creating or initializing the object is expensive (e.g. you need to read the value from a database).
When a static variable is declared, a copy of it is created. The main purpose these are used in place of a local variable is that they retain the value assigned in the scope where it is present. The programmer does not need to initialize the variable again and again in the new scope of a program.
If it were not an embedded system, you would probably be correct: I would bet that the programmers were unclear on the concept of the static, and must have meant to write this:
static int foo = 0;
static int bar = 0;
static int baz = 0;
However, in an embedded system they could have used static
to avoid allocating the variables in the automatic storage (i.e. on the stack). This could save a few CPU cycles, because the address of the static variable would be "baked into" the binary code of the compiled method.
In this context the static memory is allocated only once. The problem with this code is the initialization. If it's being reset at every execution, these variables should exist on the stack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With