Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What is the function of static variable in C++

Shulou Source: shulou.com Published: 2022-06-02 08:08:56 09月19日 Update

This article to share with you is about the role of static variables in C++, Xiaobian think quite practical, so share to everyone to learn, I hope you can read this article after some gains, not much to say, follow Xiaobian to see it.

When static modifies variables, there are two things to note.

1. The storage area for variables is global, regardless of whether the variables are in function bodies, classes, or cpp files.

2. The scope of a variable is within {}, which is closest to it, and cannot be used outside {}.

The specific scenario can refer to the following example, the compiler is G++ under Linux.

The code is as follows:

To compare the difference, the variable name is a here, and the discovery can be compiled. This also indicates that G++ has done processing to distinguish variables in different scopes.

To find out why, I compiled the assembly, the command G++ -S *.cpp.

The assembly code is as follows:

From top to bottom, we can see that variables static int a;

The variable is preceded by the corresponding function name, for example:

1. In the main function, it becomes_ZZ4mainE1a;

2. In the Fun function, becomes_ZZ4FunvE1a;

3. Global variable, becomes_ZE1a;(not pasted here, added later.)

The above is what the role of static variables in C++ is, Xiaobian believes that some knowledge points may be what we see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Variables functions actions compiling Clearing different Code Global more knowledge articles facets practical examples regions causes names commands scenarios that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft macOS Apple Redmi Linux