Home >Backend Development >C++ >When are function-level static variables in C initialized?

When are function-level static variables in C initialized?

Linda Hamilton
Linda HamiltonOriginal
2024-11-15 09:39:03340browse

When are function-level static variables in C   initialized?

Function-Level Static Variable Initialization

In C , function-level static variables are a useful mechanism for maintaining state within functions. However, their allocation and initialization process sometimes raises questions.

Unlike globally declared variables, which are allocated and initialized at program start, function-level static variables are not allocated or initialized until the function is called for the first time.

Consider the following code snippet:

void doSomething()
{
  static bool globalish = true;
  // ...
}

In this example, the static variable globalish will not be allocated or initialized until the function doSomething() is invoked. To demonstrate this, let's analyze a test program:

#include <iostream>

class test
{
public:
  test(const char *name) : _name(name)
  {
    std::cout << _name << " created" << std::endl;
  }

  ~test()
  {
    std::cout << _name << " destroyed" << std::endl;
  }

  std::string _name;
};

test t("global variable");

void f()
{
  static test t("static variable");
  test t2("Local variable");

  std::cout << "Function executed" << std::endl;
}

int main()
{
  test t("local to main");

  std::cout << "Program start" << std::endl;

  f();

  std::cout << "Program end" << std::endl;
  return 0;
}

Upon compilation and execution, the output reveals that the constructor for the static variable t in function f() is not called until the function is invoked for the first time:

global variable created
local to main created
Program start
static variable created
Local variable created
Function executed
Local variable destroyed
Program end
local to main destroyed
static variable destroyed
global variable destroyed

Therefore, function-level static variables are not allocated or initialized at program start, but rather at the first invocation of the function in which they are defined.

The above is the detailed content of When are function-level static variables in C initialized?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn