Joke Collection Website - Mood Talk - How to use static in c language? Can you tell me a password?

How to use static in c language? Can you tell me a password?

Refer to friend litaolxz's answer:

In C language, the literal meaning of static can easily lead us astray. In fact, it has three functions.

(1) The first function: hiding.

When we compile multiple files at the same time, all global variables and functions without static prefixes have global visibility. To understand this sentence, let me give you an example. We need to compile two source files at the same time, one is a.c and the other is main.c

The following is the content of a.c.

# include & ltcstdio & gt add this sentence.

Char a =' A// global variable

Void message ()

{

printf(" Hello \ n ");

}

You may ask: Why can the global variable A and the function msg defined in a.c be used in main.c? As mentioned earlier, all global variables and functions without static prefixes have global visibility, and other source files can also be accessed. In this example, a is a global variable and msg is a function. They have no static prefix, so they are visible to another source file, main.c

If static is added, it will be hidden from other source files. For example, add static before the definitions of a and msg, and main.c will not be visible. With this feature, you can define functions and variables with the same names in different files without worrying about naming conflicts. Static can be used as a prefix for functions and variables. For functions, the function of static is limited to hiding, while for variables, static has the following two functions.

(2) 2) The second function of static is to keep the content of variables persistent. Variables stored in the static data area will be initialized at the beginning of the program, which is the only initialization. * * * There are two kinds of variables stored in static storage area: global variables and static variables, but compared with global variables, static can control the visible range of variables. After all, static electricity is still used for hiding.

(3) 3) The third function of static is to initialize to 0 by default. In fact, global variables also have this attribute, because global variables are also stored in the static data area. In the static data area, the default value of all bytes in memory is 0x00, which can sometimes reduce the workload of programmers.

Finally, summarize the three functions of static in one sentence. First of all, the main function of static is hiding. Secondly, because a static variable is stored in a static storage area, it is persistent, with a default value of 0.

The following is the content of main.c

In addition to the header file, you need to declare the function: Voidmsg ();

int main(void)

{

External character a; //External variables must be declared before use.

printf("%c ",a);

(void)msg();

Returns 0;

}