C Exercise Example 41 - static
Title:Learn the usage of static to define static variables.
In C language, the static keyword is used to declare static variables. Static variables are different from ordinary variables; their lifetime and scope are different.Static variables are initialized at declaration, initialized only once, and remain in existence throughout the program's lifetime. Static variables declared inside a function can only be accessed within that function, while static variables declared outside a function can only be accessed within that file.
Program analysis:In the following example, the foo() function declares a static variable x and initializes it to 0. Each time the foo() function is called, the value of x is incremented by 1, and the new value is printed. Because x is a static variable, it exists throughout the entire lifetime of the program, not just during function calls. Therefore, each time foo() is called, it can remember the value of x and increment it based on that.
Example
The output result of the above example is:
1 2 3other extensions