Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To create a persistant variable is it better to have a local static variable or a global?

Tags:

c++

c

static

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?

like image 369
code_fodder Avatar asked Oct 17 '13 08:10

code_fodder


People also ask

When might we prefer to use a static variable over a global variable?

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 .

When should a static local variable be used?

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.

Are static variables persistent?

A static variable will persist its value throughout the lifetime of the process and only one will exist per class, not instance.

Are static variables more efficient?

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.


1 Answers

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.

like image 116
Yu Hao Avatar answered Sep 20 '22 06:09

Yu Hao