Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static initializer inside member function require compile-time constant?

Tags:

c++

c

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.

like image 836
johnbakers Avatar asked Jul 26 '26 09:07

johnbakers


2 Answers

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).

like image 104
6502 Avatar answered Jul 27 '26 23:07

6502


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++.

like image 34
Clifford Avatar answered Jul 27 '26 23:07

Clifford