简体   繁体   中英

Declaration and placement of static variable

Does X initialize by Y only once when the function is executed in the first time?

int foo(int y) {

   static int x = y;
   x = x + 1;
   return x;
}

while(1) {
  y = y+1;
  foo(y);
}

No, it is invalid to initialize a static variable with the local variable.

static inside a function is just like this, for example.

int foo(void)
{
   static int y = 0;
}

The above statement is equal to the following two things:

 1) static int y = 0;
    int foo(void)
    {

    }

 2) And the variable y' should be used only in the function foo(). So you are 
    telling the compiler that I want a variable that is a global(with respect
    to memory and initialization at the compilation time), but the variable
    should be used only inside the function, if it is used outside this function
    let me know. 


 So, dynamic initialization of a static variable(that is actually initialized at
 the time of compilation) is invalid.

Your current code is invalid, because you need to initialize static variables with constants, and y is not a constant.

foo.c:2:20: error: initializer element is not a compile-time constant
    static int x = y;
                   ^

If, on the other hand, your code looked like:

int foo() {
   static int x = 0;
   x = x + 1;
   return x;
}

Then I would expect the response from foo to be one larger each call. So the first call would return 1 , the second call would return 2 , and so on.

To fix up your foo() , so that the static x is set to the argument y only on the first call of foo() (and to make it legal C code), you will need to do something like:

int foo(int y) {
   static int init;
   static int x;
   if (!init) {
      init = 1;
      x = y;
   }
   x = x + 1;
   return x;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM