The difference and usefulness of static and const

Source: Internet
Author: User
Tags visibility

Const SUMMARY


1. Constant object: Const class Name Object name [()]
For example, const Cdate D1 (2008,8,8)
D1 is a constant object, the value of all members in the object D1 cannot be modified, the defined constant must have an initial value, cannot be left, and if a constant object is defined, you cannot call the non-const member function of the object, you can only access the const member function, and if you want the member function to access the constant object, You simply declare the member function as Const.
Like what:

void print () const,//error d1.print if no const
()


2. Pointer constants: Constant pointers//The pointer itself is a constant (pointer constant)
The value of the int *const p=&a;//pointer p cannot be modified
So the pointer constant must be initialized at declaration time, specifying the value of an address that must point to a variable, the value of the pointer constant cannot be modified, that is, cannot be replaced with a new address, cannot point to another constant, but you can modify the value of the variable it points to by using a pointer constant

3. Constant pointer: Pointer to constants//a pointer to a constant or point to a normal variable is a constant
The value of the const int *P//pointer p can be modified, which means that you can point to another constant
The constant pointer cannot modify the constant pointed to by the pointer, but the pointer can point to another constant because the pointer p itself is a variable, but it is pointing to a constant

4. The function parameter is const:
int func (const int &)
The value of a parameter cannot be modified in a function body

5. The function return value is a const reference:
const int &func (int)
The function return value is a const reference, that is, the function value cannot be modified, and assigning a const to another const reference makes sense

6. Constant data member variable:
const int age; Age is a member variable
The value of a constant data member cannot be changed, and the constant data member variable can only be initialized through the initialization list of the constructor, not by a general method of assigning values in the constructor.
For example: cstudent::cstudent (int a): Age (a) {}
cstudent::cstudent (int a)
{Age=a}//this is wrong

7. Regular member function:
void print () const; Print () is a member function
A regular member function can only access data members of this class (both const and non-const data members), but cannot modify their values, and only regular member functions are allowed to manipulate constants or constant objects
Add the const keyword to the implementation without adding a const to the call

Static summary

1. Static local variables: Static local variables always exist, the lifetime of the entire source program, the scope and local variables are the same, static local variables will be automatically initialized to 0.

2. Static global variables: Static global variables can only be used in one file

3. Static data member Variable: Describes the characteristics of the entire class, is a member of the entire class, not a member of an object
static int i;
Initializes static data members outside of the class body and is not preceded by static to avoid confusion with general static variables
Normally initialized in CPP, format
int cstudent::num = 0;

4. Static member functions: member functions that belong to the entire class, is a member of the entire class, not a member of an object, its invocation form can be invoked with an object, or it can be invoked with the name of the class, and a static member function can have a class name through:: Direct invocation, but non-static member functions can only be invoked through object names.
Static member functions do not have this pointer, you can directly access static members of the class and static member functions, not directly manipulate Non-static member variables and non-static member functions, if you want to reference non-static members in static member functions, you can use the object to reference,


static function:

In C, the literal meaning of static is easy to lead us astray, in fact, it has a role of three.
(1) The first role: hidden.
When we compile multiple files at the same time, all global variables and functions without a static prefix have global visibility. To understand this sentence, I say for example. We want to compile two source files at the same time, one is A.C and the other is main.c.
Here's what a.c.

#include <cstdio> Add this statement
char a = ' a ';//global variable
void msg ()
{
printf ("hello\n");
}


You might ask: Why global variables A and function msg defined in A.C can be used in MAIN.C.

As mentioned earlier, all global variables and functions without a static prefix have global visibility and other source files can be accessed. In this example, a is a global variable, MSG is a function, and neither has a static prefix, so main.c is visible for another source file.
If static is added, the other source files are hidden. For example, add static,main.c to the definition of a and MSG before you can 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 a function, static is limited to hiding, and for a variable, static has the following two effects.
(2) The second function of static is to keep the variable content persistent. A variable stored in a static data area completes initialization and is only initialized once the program is first run. There are two variables stored in the static store: Global and static variables, but compared to global variables, static can control the scope of the variable, in the final analysis static or to hide.
(3) The third function of static is to initialize the default to 0. In fact, global variables also have this attribute, because global variables are also stored in the static data area. In the static data area, all the byte defaults in memory are 0x00, which can sometimes reduce the programmer's workload.
Finally, the static three function to do a summary of the sentence. The main function of the static first is to hide, and second, because the static variable is stored in the quiescent store, it has a persistence and default value of 0.
Here's what main.c.
In addition to the header file, you need to declare the function: void msg ();

int main (void)
{
extern char A;//extern variable must is declared before use
printf ("%c", a);
(void) msg ();
return 0;
}


The benefits of static:

The global variable is defined as a global static variable before the global variable is added with the keyword static.
1 in-memory location: static storage (static storage exists throughout the program's operation)
2 initialization: Uninitialized global static variables are automatically initialized by the program to 0 (the value of the automatic object is arbitrary unless he is shown initialized)
3 scope: Global static variable is not visible outside of declaring his file. Start at the end of the file exactly as defined.

Benefits:
The benefits of defining global static variables:
<1> will not be accessed by other files, modify
<2> Other files can use the same name of the variable, there will be no conflict.

Local static variables
The local variable is defined as a local static variable before the local variable is added with the keyword static.
1 position in memory: static storage area
2 initialization: Uninitialized global static variables are automatically initialized by the program to 0 (the value of the automatic object is arbitrary unless he is shown initialized)
3 Scope: Scope is still a local scope, when the function that defines it or the statement block ends, the scope ends.

Note: When static is used to modify a local variable, it changes the storage location of the local variable, and changes it from the original stack to a static storage area. But the local static variable, after leaving the scope, is not destroyed, but still resides in memory until the end of the program, but we can no longer access him.
When static is used to decorate a global variable, it changes the scope of the global variable (not visible outside the declaration of his file), but does not change its location or in a static storage area.

3. Static function
The function is defined as a static function by adding the keyword static before the return type of the function.
The definition and declaration of a function are extern by default, but a static function is only visible in declaring his file and cannot be used by other files.
The benefits of defining static functions:
<1> other files can be defined with the same name of the function, there will be no conflict
<2> static functions cannot be used by other files. Storage specifier auto,register,extern,static, corresponding to two storage periods: automatic storage period and static storage period. Auto and register correspond to the automatic storage period. A variable with an automatic storage period is established when it enters the program block that declares the variable, it exists when the block is active, and is revoked when it exits the program block.
The keyword extern and static are used to describe variables and functions that have a static storage period. Local variables declared with static have either a static storage duration (static storage duration), or a static range (static extent). Although his value remains valid between function invocations, the visibility of its name is still limited to its local domain. A static local object is first initialized when the program executes to the declaration of the object.
Because of the above characteristics of static variables, some specific functions can be implemented.
such as statistical frequency function
Declares a local variable of a function and is set to the static type as a counter so that the function can be counted each time it is invoked. This is the best way to count the number of times a function is called, because the variable is related to the function, and the function may be invoked in several different places, so it is difficult to count from the caller's point of view.


The benefits of using static functions in the C language:
Static functions are automatically assigned to a storage area that is always in use until the application instance is exited, avoiding the call function when the stack is pushed out, much faster.
The keyword "static", translated into Chinese is "still", so the internal function is also called static function. But the meaning of "static" here is not the way of storage, but the scope of the function is limited to this file. The advantage of using internal functions is that when different people write different functions, they do not have to worry about the functions they define, whether they will have the same name as the functions in other files, because the same name does not matter.


The semantics of static in C language

1.static variable:

1. Local A. Static local variables are defined within the function, the lifetime is the entire source program, but the scope is the same as the automatic variable and can only be used within the function that defines the variable. After exiting the function, it cannot be used, although it continues to exist. B. For static local variables of the basic type if the initial value is not assigned in the description, the system automatically assigns a value of 0. For an automatic variable, the value is indeterminate.

2. Global global variable itself is the static storage mode, static global variable is of course also static storage mode. But their scope, the scope of a non-static global variable is the entire source program (multiple source files can be used together), while a static global variable restricts its scope, which is only valid within the source file that defines the variable, and cannot be used in other source files of the same source program.

2.static function (also called intrinsic function)

Can only be called by functions in this file, not by functions in other files of the same program. Different from the General non-static function (external function) static in C can be used to modify variables, can also be used to modify the function. First look at the time to modify the variable. Variables in C can be divided into the existence of global data areas, stacks and heaps. In fact, we usually say the stack is stack and does not contain the right, do not confuse. --by Damon

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.