For example there is a function doing something. How should i declare and define an array inside the function i’d like to be allocated/initialized only once?
void someclass::somefunction(/*parameters here*/)
{
static const my_array[4] = {1,2,3,4}; // #1
/*or just*/
const my_array[4] = {1,2,3,4}; // #2
}
As far as i know in the case #1 “my_array” will be allocated in data segment and initialized once at the first time of “somefunction” calling. But a colleague of mine made an supposition that the case #2 works in the same manner and there is no need to write “static” key-word.
So i’d like to ask does the standart say something about cases #1 & #2 and, if it does, what exactly? How should i define such type of arrays to be sured that it will be allocated/initialized only once?
Thank you.
Declare and define it the most logical and clear way, and only if profiling shows it to be a bottleneck would I suggest changing the code.
In this case some compilers may very well generate the same code. Others may generate different code due to the slightly different initialization semantics (for example in some cases g++ protects initialization of statics with a mutex lock).
In fact the only way to know for sure for your particular compiler is to look at the disassembly.