The role of keywords auto, static, register, const, volatile, extern in C language

Source: Internet
Author: User
Tags volatile microsoft c

Original: The role of the keyword auto, static, register, const, volatile, extern in C language

Keyword auto, static, register, const, volatile, extern

These keywords are basic knowledge of C + +, I have organized a bit, I hope to be useful to the newly-learned friends:

(1) Auto
This keyword is used to declare that the lifetime of a variable is automatic, and that variables defined in any class, struct, enumeration, union, and function are not treated as global variables, whereas variables defined in a function are considered local variables. This keyword doesn't write much, because all variables are auto by default.

(2) Register
This keyword command compiler as far as possible to have variables in the CPU internal registers rather than through memory addressing access to improve efficiency.

(3) static
There are two common uses:
1> the number of times the statistic function was called;
2> reduces the overhead of local array creation and assignment. The creation and assignment of variables is required for a certain amount of processor overhead, especially for storage types that contain more elements such as arrays. In some functions that have more variables and are often called, you can declare some arrays as static types to reduce the overhead of establishing or initializing these variables.
Detailed Description:
1>, variables are placed in the program's global store so that the original assignment can be maintained at the next call. This is the difference between a stack variable and a heap variable.
2>, variables with static tells the compiler that it is only visible within the scope of the variable. This is the difference between it and the global variable.
3> when static is used to modify a global variable, it changes the scope of the global variable so that it cannot be placed in the current file by another program extern, but does not change its location or is in the global static storage area.

Use Note:
1> If the global variable is accessed only in a single C file, you can modify the variable to a static global variable to reduce the coupling between the modules;
2> If the global variable is accessed only by a single function, the variable can be changed to a static local variable of the function to reduce the coupling between the modules;
3> design and use functions that access dynamic global variables, static global variables, and static local variables, you need to consider the reentrant problem (the same output should be produced as long as the input data is the same).

(4) const
The const-modified items are protected against accidental changes and can improve the robustness of the program. It can modify the parameters of the function, the return value, or even the definition body of the function.
Role:
1> Modifying input parameters
A. For input parameters of non-internal data types, the "value passing" method should be changed to "const reference passing" to improve efficiency. For example, void Func (a a) is changed to void func (const a &a).
B. For input parameters of the internal data type, do not change the "value passing" method to "Const reference pass". Otherwise, it can not achieve the purpose of improving efficiency, but also reduces the comprehensible function. For example, void func (int x) should not be changed to void func (const int &x).
2> The return value of the const modifier function
A. The contents of a function return value (that is, the pointer) cannot be modified if the function return value of the "pointer Pass" method is added to the const modifier, and the return value can only be assigned to a const-decorated pointer of the same type.
For: const char * GetString (void);
A compilation error will appear in the following statement:
Char *str = GetString ();//cannot convert from ' const char * ' to ' char * ';
The correct usage is:
const char *STR = GetString ();
B. If the function return value is in "value passing", the const modifier has no value because the function copies the return value into an external temporary storage unit. Do not write the function int GetInt (void) as a const int GetInt (void).
In the declaration of a 3>CONST member function, the const keyword can only be placed at the end of a function declaration, indicating that the class member does not modify the object.
Description
Const type M; Modifier m is not a change
Example:
typedef char * PSTR; new type of pstr;
Char string[4] = "ABC";
const char *P1 = string;
p1++; Right, the top modifier is *P1,P1 variable
Const PSTR P2 = string;
p2++; Error, the top modifier is P2,P2 immutable, *P2 variable
Similarly, the const modifier pointer is not confused when it is judged by this principle.
const int *value; *value immutable, value variable
int* const value; Value is immutable, *value variable
const (int *) value; (int *) is a type,value immutable, *value variable
Logically this understanding, compile can not pass, need tydef int* NewType;
Const int* Const value;//*value,value are not mutable

(5) volatile
Indicates that the value of a variable may be changed externally, and the optimizer must carefully reread the value of the variable each time it is used, rather than using the backup stored in the register. It can be applied to basic types such as: Int,char,long ... Also applies to C's structure and C + + classes. When you use a volatile modifier on a struct or class object, all members of the struct or class are treated as volatile.
This keyword is often used in multi-threaded environments, because when writing multithreaded programs, the same variable can be modified by multiple threads, and the program synchronizes each thread through that variable.
Simple example:
   

    1. DWORD __stdcall ThreadFunc (LPVOID signal)
    2. {
    3. int* intsignal=reinterpret_cast (signal);
    4. *intsignal=2;
    5. while (*intsignal!=1)
    6. Sleep (1000);
    7. return 0;
    8. }

The thread starts with intsignal set to 2, and then loops until intsignal exits 1 o'clock. It is obvious that the value of intsignal must be changed externally, otherwise the thread will not exit. However, the thread does not exit when it is actually running, even if it is externally changing its value to 1, look at the corresponding pseudo-assembly code to understand:
MOV ax,signal
Label
if (ax!=1)
Goto Label
For the C compiler, it does not know that this value will be modified by another thread. Naturally, it caches it in the register. The C compiler does not have a threading concept, and it needs to use volatile. Volatile is intended to mean that this value may be changed outside the current thread. That is, we want to add the volatile keyword in front of the intsignal in ThreadFunc, when the compiler knows that the value of the variable changes externally, so each time the variable is accessed it is reread and the loop becomes as shown in the following pseudo-code:
Label
MOV ax,signal
if (ax!=1)
Goto Label
Note: A parameter can be both const and volatile, which is volatile because it can be unexpectedly changed. It is const because the program should not attempt to modify it.

(6) extern
extern means "foreign" ... Its purpose is to tell the compiler that there is a variable that may not exist in the current file, but it must exist in a source file in the project or in the output of a DLL.

The following is a few key words about C + + are often dealing with us and we often vague about these, this article according to their own learning experience to summarize, in order to achieve the purpose of real understanding and utilization.

Static
Static variables are scoped to a file, the program starts with space allocated, the space is freed at the end, the default is initialized to 0, and its value can be changed when used.
static variable or static function, that is, only the code within this file can access it, its name (variable name or function name) is not visible in other files.
L Static variables generated in the function body its value can only be maintained

    1. int Max_so_far (int curr)//The maximum value so far (this call)
    2. {
    3. static int biggest; The variable maintains the most recent value at each invocation, and its validity is equal to the duration of the entire program
    4. if (Curr > Biggest)
    5. biggest = Curr;
    6. Return biggest;
    7. }

A member variable in a C + + class is declared as static (called a statically member variable), which means that it is shared with all instances of the class, that is, when an instance of a class modifies the static member variable, its modified value is seen by all other instances of the class, and the static member function of a class can only access static members (variables or letters Number).
The static member variable of the L class must be initialized within the scope of the file in which it is declared to be used, and the private type is no exception. Such as
float savingsaccount::currentrate = 0.00154;
(Note: CurrentRate is a static member variable of class SavingsAccount)
Register
The variable declared with register is called a register variable, which, if possible, is stored directly in the machine's register, but does not work for the 32-bit compiler, and when global optimizations is on, it makes a choice whether to put it in its own register; Other symbols related to the Register keyword are valid for 32-bit compilers.

Auto
L It is a storage type identifier that indicates that the variable (auto) has a local scope, and a block-scoped variable declaration (such as a variable declaration in the For Loop body) defaults to the auto storage type.
extern
L Declare a variable or function to be an external link, that is, the variable or function name is visible in other files. The variable (external variable) that is modified is statically allocated space, that is, when the program starts and is disposed at the end. The variable or function declared with it should be defined (implemented) in another file or elsewhere in the same file. Declare a variable or function in the file by default to be externally available.

In C + +, you can also use to specify a link in another language that needs to be used with a specific translator. Currently, Microsoft C + + is only supporting C-compiler links with "C" conversion tokens. There are two forms of using this case:

u extern "C" declaration statement

u extern "C" {declaration statement block}

Volatile
L limit an object to be changed by an external process (operating system, hardware, or concurrent threads, etc.) with the following syntax:

int volatile nvint;
Such declarations are not most efficient because their values change at any time, and the system often reads and writes the values of this object when needed. is used only for memory unit access, such as an interrupt handler, for asynchronous processes.

Const
A const modified object or variable cannot be altered, and when the function is modified, the function cannot alter the variable declared outside of the function and cannot invoke any non-const function. A const is added to the declaration and definition of a function after the last parenthesis in the function argument list.
In C + +, declaring a variable with a const means that the variable is a constant with a type that can replace # define and one more type information than # define, and that it executes an inner link that can be declared in the header file, but in C, its declaration must be placed in the source file (that is, the. c file), the const declares a variable in C, except that it cannot change its value, which is still a variable, such as
const int Maxarray = 255; It55.com
Char Store_char[maxarray]; Legitimate in C + +, illegal in C
L
You should pay special attention to the const modifier pointers. Cases:

    1. char *const aptr = mybuf; Constant pointer
    2. *aptr = ' a '; Legal
    3. Aptr = Yourbuf; Error
    4. const char *bptr = MYBUF; (pointer bptr) points to constant data
    5. *bptr = ' a '; Error
    6. Bptr = Yourbuf; Legal

The Const modifier member function cannot be used for construction and destructors.

The role of keywords auto, static, register, const, volatile, extern in C language

Related Article

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.