How is static variable initialization implemented by the compiler?

前端 未结 5 2049
旧巷少年郎
旧巷少年郎 2020-12-02 11:50

I\'m curious about the underlying implementation of static variables within a function.

If I declare a static variable of a fundamental type (char, int, double, etc.

5条回答
  •  感情败类
    2020-12-02 12:17

    I know that it will not be initialized until the first time that the function is called. Since the compiler has no way of knowing when the function will be called for the first time, how does it produce this behavior? Does it essentially introduce an if-block into the function body?

    Yes, that's right: and, FWIW, it's not necessarily thread-safe (if the function is called "for the first time" by two threads simultaneously).

    For that reason you might prefer to define the variable at global scope (although maybe in a class or namespace, or static without external linkage) instead of inside a function, so that it's initialized before the program starts without any run-time "if".

提交回复
热议问题