0

Let's say I have a class A which contains a static const int array like the following.

class A {
    static const int _array[];
    static int fn( int n );
}

Function fn includes very heavy calculation. And now I want to initialize my static const array using the function fn.

I did that in the following way:

//.cpp file
int A::fn (int n){
    ....
    return ....
}
const A::_array[] = {
    fn(0);
    fn(1);
    fn(2);
    ...
    fn(9);
}

My question is that whether the array initialization is in compile time? And how many times does the fn run if I use _array[i] in my other class methods? only 10 times in its initialization or it depends on how many times I use the _array?

EDIT: it was c++03 and is there any more efficient way to do this?

4
  • C++11 or C++03 ? is fn can be constexpr ?
    – Jarod42
    Commented Feb 25, 2014 at 15:42
  • How can it be at compile time if fn has to perform user interaction, network IO and random number generation?
    – Kerrek SB
    Commented Feb 25, 2014 at 15:44
  • Shouldn't that be const int A::_array[] = ... in the cpp?
    – Axel
    Commented Feb 25, 2014 at 15:53
  • yes, it's A::_array[]
    – ddennis
    Commented Feb 25, 2014 at 15:56

1 Answer 1

1

The array is initialized at run-time. But it will be initialized before the control will be passed to main. it could be initialized at compile time if it and the function would be defined as constexpr But such functions can not have very heavy calculations.

The function will be called as many times as there are its calls in the initialization list.

Also the correct definition of the array is

const int A::_array[] = {

Not the answer you're looking for? Browse other questions tagged or ask your own question.