Lets say you have a class (c++) or module (single c file). Then in one of your functions you want to store a copy of a variable and hold its value until the next time the function is called, is it better to have a global (could be private in c++ and not extern'd in c to keep it in the module scope) or make a local static variable?
e.g.:
void some_func_that_does_not_do_anything_useful(int arbVal)
{
static int lastArbVal = 0;
if (arbVal > lastArbVal)
{
lastArbVal = arbVal;
}
}
The reason I would make a static is to keep its scope as limited as possible, but certain things I read suggest you should use globals for this, so now I am confused.
What is best (if any)?, pros/cons?
If global variable is to be visible within only one . c file, you should declare it static. If global variable is to be used across multiple .
Static local variables are useful when we want to have only one instance of our object in the local scope, which means all calls to the function will share the same object. The same can also be achieved by using global variables or static member variables.
A static variable will persist its value throughout the lifetime of the process and only one will exist per class, not instance.
Using static variables may make a function a tiny bit faster. However, this will cause problems if you ever want to make your program multi-threaded. Since static variables are shared between function invocations, invoking the function simultaneously in different threads will result in undefined behaviour.
The rule here is simple: if the variable needs to be accessed by more than one functions, make it global. If not, static
variables inside functions are usually better. One of the pros is it avoids polluting the global namespace.
Note that if a global variable doesn't need to be accessed outside the file, it's better to declare it as file-scope variable(i.e, declare it as static
)
Back to your example, I think it's best to use static
variable like you already did.
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