8

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?

8
  • 2
    If you only use it in that function, and nowhere else, then making it static is probably the best solution. Though you might want to think about cases like multi-threading, as the static variable will be shared between all threads. Commented Oct 17, 2013 at 8:32
  • In the interest of encapsulation a local static would be best. This is also the approach many C functions take. strtok comes to mind. Commented Oct 17, 2013 at 8:32
  • 1
    To quote from the strtok man page: "Never use these functions". Let's not use that as an example of how to do things :-) Commented Oct 17, 2013 at 8:38
  • Can you share the resource/s from where you read that you should use globals in this case? Commented Oct 17, 2013 at 8:39
  • No the example shows pretty much how I have it in my code. Its all within this one function and not used anywhere else :) Commented Oct 17, 2013 at 9:32

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

An alternative to file-scope static is an anonymous namespace.
One more reason file scope static might not be suitable is static initialization order. If the function that uses it is called during initialization of other statics from different translation units, then you're in for trouble.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.