C + + local variables, global variables, static variables (heap, stack, static storage area)

Source: Internet
Author: User

1 Static keyword

1.1 Hidden

eg

In the A.C file

char a = ' a ';

void msg ()

{

printf ("hello\n");

}

In the Main.c file

extern char A;

printf ("%c", a);

Output Result: A Hello

all global variables and functions that do not have a static prefix have global visibility, and other source files can be accessed. A is a global variable, MSG is a function, and neither has a static prefix, so MAIN.C is visible for additional source files.

If Static is added, it is hidden from other source files. For example, before the definition of a and MSG, add STATIC,MAIN.C to see them. With this feature, you can define a function with the same name and a variable of the same name in different files without worrying about naming conflicts. Static can be used as a prefix for functions and variables, and for functions, static is limited to hiding.

1.2 Persisting variable content (memory function and global lifetime in static variables)

eg

# include <stdio.h>

int fun () {

static int count = 10; The first time you enter this function, the variable A is initialized to 10! And then subtract 1, and each time you enter the function, a

return count--; will not be initialized again, only the operation of the self minus 1, before the static invention, to achieve the same function, you can only use global variables:

}

int count = 1;

int main (void)

{

printf ("Global\t\tlocal static\n");

for (; Count <=; ++count)

printf ("%d\t\t%d\n", Count, Fun ());

return 0;

}

Output Result:

Global local static

1 10

2 9

3 8

4 7

5 6

6 5

7 4

8 3

7 |

10 1

Variables stored in the static data area are initialized at the start of the program and are the only one initialized. A total of two variables are stored in static storage: Global variables and static variables, except that, compared to global variables, static can control the visible range of variables, in the final analysis, static is used to hide them.

---Based on the above two points can be drawn to a conclusion: the change of the local variable to a static variable is changed its storage mode, which changes its lifetime . Changing a global variable to a static variable changes its scope and limits its scope of use . So the function of the static descriptor is different in different places.

1.3 Default initialized to 0 (static variable)

In fact, global variables also have this property, because global variables are also stored in the static data area. In the static data area, all bytes in memory default values are 0x00, sometimes this feature can reduce the workload of the programmer. For example, to initialize a sparse matrix, we can place all the elements in one place 0, and then assign values to elements that are not 0. If it is defined as static, it eliminates the first 0 operation. Another example is to put a character array as a string to use, but also feel each time at the end of the character array to add ' + '; too troublesome. If the string is defined as static, it saves the trouble, because it is already ' the '.

1.4 Class member declarations in C + + static (some places overlap with the above functions)

The static member function does not contain the this pointer.

Static members can be accessed independently, that is, without creating any object instances.

A static member function of a class is an object of the entire class rather than a class, so it does not have the this pointer, which causes it to access only the static data and static member functions of the class.

2 local variables, global variables, static variables

Local variables: Local variables are also only local scope, it is an automatic object (auto), it does not persist during the program run, but only during the execution of the function, the function of the execution of a call after the end of the variable is revoked, the memory occupied by the recovery.

Global variables: Global variables have global scope. A global variable can be used for all source files simply by defining it in one source file. Of course, other source files that do not contain global variable definitions need to declare the global variable again with the extern keyword.

Static local variable: the static local variable has a local scope, it is initialized only once, since the first time it was initialized until the end of the program runs, it differs from the global variable in that the global variable is visible to all functions, while the static local variable is always visible to the body of the function that defines itself.

static Global variables: Static global variables also have global scope, which differs from global variables in that if a program contains multiple files, it acts on the file that defines it and does not work in other files, that is, variables modified by the static keyword have a file scope. This way, even if two different source files define static global variables of the same name, they are also different variables.

3 stacks

Also known as dynamic memory allocation. The program uses malloc or new to request any size of memory at run time, and the programmer is responsible for freeing the memory with free or delete when appropriate. The lifetime of dynamic memory can be determined by us, and if we do not release the memory, the program will release the dynamic memory at the end. However, good programming habits are: If a dynamic memory is no longer used, it needs to be released, otherwise, we think there is a memory leak phenomenon.

When a memory unit needs to be opened in C + +

char* str = new CHAR[100];

Remember to release the memory unit when you're done with it.

Delete[] STR;

str = 0;

4 Stacks

When executing a function, the storage units of local variables within the function can be created on the stack, which are automatically freed when the function is executed at the end. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.

int A;

5 Static Storage Area

Memory is allocated at the time of program compilation, and the entire running period of the program is present in this block. It mainly stores static data, global data, and constants.

Global variables

Static modified variables or functions, etc.

Let's look at the differences between these types of storage areas:

Example 1: Static storage and Stack area

char* p = "Hello World1";

Char a[] = "Hello World2";

P[2] = ' A ';

A[2] = ' A ';

char* p1 = "Hello World1";

This program is error, error occurs in p[2] = ' A ' This line of code, for what, is the variable p and variable array A all exist in the stack (any temporary variables are in the stack, including the variables defined in the main () function). However, the data "Hello World1" and the data "Hello World2" are stored in different regions. Because the data "Hello World2" exists in the array, this data is stored in the stack area, and there is no problem with its modification. Because the pointer variable p is only able to store the address of a storage space, the data "Hello World1" is a string constant, so it is stored in a static storage area. Although through p[2] you can access the third unit of data in the static store, the unit of storage where the character ' L ' resides. However, because the data "Hello World1" is a string constant, it cannot be changed, so a memory error is reported when the program is run. Also, if the output of P and P1 at this time, it will be found that the address stored in P and P1 is exactly the same.

Example 2: Stack area and heap area

char* F1 ()

{

char* p = NULL;

Char A;

p = return p;

}

char* F2 ()

{

char* p = NULL;

p = (char*) new char[4];

return p;

}

Both of these functions return the address of a storage space, what is the difference between them? The F1 () function returns a storage space, but this space is a temporary space. In other words, this space has only a short life cycle, and its life cycle at the end of the function F1 () call loses its life value, namely: this space is freed. So, when you call the F1 () function, if you have the following statement in your program:

Char* p;

p = F1 ();

*p = ' a ';

At this point, the compilation does not report an error, but an exception error occurs when the program is run. Because you're working on memory that should not be manipulated (that is, the storage space that has been freed). However, in contrast, the F2 () function does not have any problems. Because the new command is to request storage space in the heap, once the application succeeds, the memory will persist unless you delete it or terminate the program. It can also be understood that heap memory is a shared unit that can be accessed by multiple functions together. Heap memory is a good choice if you need to have more than one data return but no way.

In summary, the biggest difference between heap, stack, and static storage is that the life cycle of the stack is short. However, the life cycle of the heap and static stores is equivalent to the life of the program (if you do not delete the heap memory in the middle of the program run), we make this variable or data a global variable or data. However, the memory space usage of the heap area is more flexible because it allows you to free it at any time when it is not needed, while the static storage will always exist throughout the lifetime of the program.

C + + local variables, global variables, static variables (heap, stack, static storage area)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.