2

In the C language, in order to initialize a static local variable to a value unknown during compilation, I would normally do something like this (for example):

void func()
{
    static int var = INVALID_VALUE;
    if (var == INVALID_VALUE)
        var = some_other_func();
    ...
}

In the C++ language, I can simply do:

void func()
{
    static int i = some_other_func();
    ...
}

The only way (that I can think of) for a C++ compiler to resolve it properly, is by replacing this code with a mechanism similar to the C example above.

But how would the compiler determine a "proper" invalid value? Or is there another way which I haven't taken into consideration?

Thanks


Clarification:

INVALID_VALUE is a value which function some_other_func never returns.

It is used in order to ensure that this function is never invoked more than once.

barak manos
  • 29,648
  • 10
  • 62
  • 114

2 Answers2

2

The compiler will not generate code to do it based on its value but on a thread safe flag that ensure that the code is only executed once.

Something like that:

void func()
{
    static int i;
    static bool i_initialized;
    if (!i_initialized) {
      i = some_other_func();
      i_initialized = true;
    }
}

Except that generally it is not a bool but a thread safe way of testing it.

Baptiste Wicht
  • 7,472
  • 7
  • 45
  • 110
  • Thank you. It's pretty much the same answer as the one given by @Dieter Lücking in one of the comments above (which makes me feel kinda stupid asking this question in the first place). – barak manos Jul 13 '14 at 10:19
1

According to code seen by disassembling and debugging the g++ compiled code, there is a hidden variable that is initialized to 0 and when the initialization is run it is set to 1. So the next time the initialization code isn't executed.

George Kourtis
  • 2,381
  • 3
  • 18
  • 28