johnbakers
johnbakers

Reputation: 24770

Static initializer inside member function require compile-time constant?

I have seen it written that:

The static initializer is executed before the first invocation of the containing function; the initializer expression must be a compile-time constant.

Consider this:

void func(){
   static float tr=((float) rand() / (RAND_MAX));
}

tr depends on a runtime function, rand(). I don't think the value of rand() is known at compile time, is it? Yet this compiles fine in C++ and a lot of answers/literature indicate that C behavior is the same as C++ in this regard.

Upvotes: 2

Views: 133

Answers (2)

Clifford
Clifford

Reputation: 93486

It is valid C++, it is not valid C.

The answer linked in the question from where the quote comes from refers to the behaviour of C, but the question is clearly specific to C++.

Upvotes: 3

6502
6502

Reputation: 114539

In C++ a local static initialization is performed the first time the scope is entered and the expression doesn't need to be a constant at all. You can call any function you like. A common patter for singletons is for example:

MySingleton& get_instance() {
    static MySingleton s;
    return s;
}

where the instance will be constructed only when (and if) the get_instance function is called. With C++11 you're even guaranteed that there will be no problem if get_instance is possibly called from multiple threads at the same time as the compiler will add the needed locking logic.

In C things are different and static initialization is performed by the loader before program starts and you can only use constant expressions so the code in your question is not valid (you cannot call rand).

Upvotes: 6

Related Questions