Home > Backend Development > C++ > When and How Are Function-Level Static Variables in C Allocated and Initialized?

When and How Are Function-Level Static Variables in C Allocated and Initialized?

Patricia Arquette
Release: 2024-11-18 02:12:02
Original
237 people have browsed it

When and How Are Function-Level Static Variables in C   Allocated and Initialized?

Allocation and Initialization of Function-Level Static Variables

Function-level static variables in C are a type of data that persists throughout the lifetime of the program. Unlike global variables, they are not declared at the global scope, but rather within the scope of a function. This raises疑問 about when these variables are allocated and initialized.

In contrast to globally declared variables, which are allocated and initialized at the start of the program, function-level static variables are allocated and initialized upon the first call to the function in which they are defined. This is evident in the example code provided:

void doSomething() {
  static bool globalish = true;
}
Copy after login

The static variable globalish is initialized upon the first call to the function doSomething. Prior to that, its value is undefined. This result was confirmed through a test program that printed events related to the creation and destruction of objects instantiated within different scopes.

This behavior is attributed to the fact that static variables are stored in a static area of memory that is shared among all calls to the same function. Thus, the initial value remains persistent across calls, unless explicitly modified within the function.

The above is the detailed content of When and How Are Function-Level Static Variables in C Allocated and Initialized?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template