C Exercise Example 41 - static

100 Classic C Examples

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

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. // #include <stdio.h> void foo() { static int x = 0; x++; printf("%d\n", x); } int main() { foo(); // Output 1 foo(); // Output 2 foo(); // Output 3 return 0; }

The output result of the above example is:

1
2
3

100 Classic C Examples

other extensions