Question

I have several functions in a program I'm writing that use a value I need to calculate with a very slow function. This value will change every time the program is rerun, so I can't just store a static value. Below is an example.

void this_gets_called_frequently()
{
    static int value = slow_function();

    //do stuff with the above value
}

My main problem here is not one of the program not working, rather of neatness. I don't really want to initialise a global variable and store the value in that, since it is not going to change once calculated. Would using the static keyword in the manner shown above only call the function above to be calculated once? Would a const keyword added in there help?

Thanks everyone, this was answered perfectly!

Was it helpful?

Solution

Yes, an initialization of local static variable will happen at most once (although I recall some compiler versions could have problems with multithreading here). const is not required, in this case it's mostly a matter of readability and taste.

OTHER TIPS

Would using the static keyword in the manner shown above only call the function above to be calculated once?

Yes, on the first invocation of this_gets_called_frequently

Would a const keyword added in there help?

No. But add const for documentation value.

Use may use the thread local variables from C++11, if they are available in your compiler. If you are on Windows, you can use similar TlsAlloc API. It is there since the dawn of Win32.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top