Initialisation of static variable with itself

后端 未结 1 964
梦毁少年i
梦毁少年i 2021-02-07 15:59

Consider following code example:

#include 

static int bar = bar;

int main()
{
    int foo = foo;
    std::cout << \"foo = \" << foo         


        
相关标签:
1条回答
  • 2021-02-07 16:52

    I believe that part of the standard is relevant to your question (§3.6.2/2):

    Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.[...]

    So in this case, even before the compiler looks at your definition of bar, it has already zero-initialized it.

    As it is specified a bit further in the standard, there shall be two phases for static variables initialization (emphasis mine).

    Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place.

    0 讨论(0)
提交回复
热议问题