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.

11
  • I'm a bit confused. What does INVALID_VALUE represent? And what's the point of it? Commented Jul 13, 2014 at 9:01
  • @JosephMansfield: I think, OP means some value some_other_func never returns to check if var has been assigned a return value of that function. Commented Jul 13, 2014 at 9:04
  • @JosephMansfield: A value which I consider invalid, and that I know some_other_func will never return (for example, if it was a pointer, then I would normally use NULL). Commented Jul 13, 2014 at 9:04
  • @mafso: Thank you for making my point clearer :) Commented Jul 13, 2014 at 9:05
  • 6
    The compiler does not need an invalid value, a flag 'initialized' will do it, even for an object with a constructor. Commented Jul 13, 2014 at 9:10

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.