Key word volatile

Source: Internet
Author: User
Tags modifier volatile
function volatileFunction: As a directive keyword, ensure that this instruction is not omitted by the compiler optimization and requires a direct read value each time. To put it simply, prevent the compiler from optimizing the code. For example, the following procedure: xbyte[2]=0x55; xbyte[2]=0x56; xbyte[2]=0x57; xbyte[2]=0x58; For external hardware, each of these four statements represents a different operation, resulting in four different actions, but the compiler cannot optimize the above four statements like a pure program, thinking only of xbyte[2]=0x58 (that is, ignoring the first three statements and generating only one machine code). If you type volatile, the compiler compiles each one and produces the corresponding machine code (four). several examples Recommending a variable that is defined as volatile is that the variable may be unexpectedly altered so that the compiler does not assume the value of the variable. Precisely, the optimizer must carefully reread the value of the variable every time it uses it, instead of using a backup stored in the register. Here are a few examples of volatile variables: 1. Hardware registers for parallel devices (e.g., status registers) 2). A non-automatic variable (non-automatic variables) 3 that is accessed in an interrupt service subroutine. A variable that is shared by several tasks in a multithreaded application the person who cannot answer this question cannot be hired. I think this is the most basic problem to differentiate between C programmers and embedded system programmers. Embedded system programmers often deal with hardware, interrupts, RTOs, and so on, all of which require the use of volatile variables. Not knowing volatile content will bring disaster. Assuming the interviewer has answered the question correctly (well, doubt it will be), I'm going to delve a little deeper and see if this guy really understands volatile's full importance. 1. Can a parameter be either a const or a volatile? explain why. 2). Can a pointer be a volatile? explain why. 3). The following function is used to compute the square of an integer, which achieves the intended design goal. If not, try to answer the question: int square (volatile int *ptr) {return *ptr * *PTR;} Below is the answer: 1). Yes. An example is a read-only status register. It is volatile because it can be changed unexpectedly. It is const because the program should not attempt to modify it. 2). Yes. Although this is not very common. An example is when an interrupt service subroutine modifies a pointer to a buffer. 3). This code is a prank. The purpose of this code is to return pointer *ptr to the square of the value, but since *ptr points to a volatile parameter, the compiler will produce code similar to the following: int square (volatile int *ptr) {int a,b; a = *ptr; b = * ptr return a * b; A and B may be different because the value of *ptr may change between two-time value statements. As a result, this code may not return the square value you expected. The correct code is as follows: Long square (volatile int *ptr) {int A; a = *ptr; return a * A;} tell me about me.The Understanding: (Welcome Tai ... ~ ~. The key is two places: ⒈ compiler optimization (please help me look at the following understanding) in this thread, when reading a variable, in order to improve the access speed, the compiler sometimes first read the variable to a register, and then take the value of the variable, directly from the register value; When the value of a variable changes in the Chengri of the line, the new value of the variable is also added to the register. In order to be consistent. When a variable changes a value because of another thread, the value of the register does not change, causing the value of the application read to be inconsistent with the actual variable value when the register is changing the value due to another thread, the original The value of the variable does not change, which results in an inaccurate example of the inconsistency between the value read by the application and the actual variable value: When the payroll is paid, the accountant calls the employee to register their bank card number every time; for the sake of convenience, the accountant did not register immediately, and used the bank card number which was previously registered; just one employee's bank card was lost, has reported the loss of the bank card number, resulting in the employee not being paid employees--the original variable address bank card number--the original variable in the register backup ⒉ under what circumstances (such as the 1 floor said) 1). Hardware registers for parallel devices (e.g., status registers) 2). A non-automatic variable (non-automatic variables) 3 that is accessed in an interrupt service subroutine. The variables that are shared by several tasks in multithreaded applications are supplemented by: volatile should be interpreted as "direct access to the original memory address" is more appropriate, "variable" This explanation is a bit misleading; "variable" is caused by external factors, like multithreading, interruptions, and not because of the volatile modified Variable is "easy to change", if there is no external cause, that is, the use of volatile definition, it will not change, and the definition of volatile, in fact, the variable will not be changed by external factors, you can rest assured that the use of; let's see if the previous explanation (variable) is misleading The------------Concise example is as follows: The------------------volatile keyword is a type modifier, and the type variable declared with it represents changes that can be made by some compiler unknowns, such as the operating system, hardware, or other threads. When you encounter a variable that is declared by this keyword, the compiler will no longer optimize the code that accesses the variable, thus providing a stable access to a particular address. Examples of using this keyword are as follows: int volatile nvint; >>>>; when asked to use the value of a variable declared by volatile, the system always reads the data back from its memory, even if the previous instruction has just read the data from that point. and read the data standEngraved is saved. For example: volatile int i=10; int a = i; ...//other code, did not explicitly tell the compiler that the I was operating int b = i; >>>>volatile points out that I is subject to change at any time and must be read from the address of I whenever it is used, so that the compiler-generated assembly code will again read the data from I to the address in B. The optimization approach is that because the compiler finds that the code in the code between the two times I read data does not operate on I, it automatically places the last read data in B. Rather than re reading from I. As a result, if I is a register variable or represents a port data is prone to error, so volatile can guarantee a stable access to special addresses. >>>>; Note that in VC6, the General debug mode is not optimized for code, so the role of this keyword cannot be seen. The following is done by inserting the assembly code, testing for the volatile keyword, and the effect on the final code of the program: >>>>; first, build a Win32 console project with ClassWizard, Insert a Voltest.cpp file and enter the following code: >> #i nclude <stdio.h> void Main () {int i=10; int a = i; printf ("I=%d", a);//The following assembly The function of the statement is to change the value of I in memory, but not to let the compiler know __asm {mov dword ptr [ebp-4],20h} int b = i; printf ("i=%d", b); } Then, running the program in debug version mode, the output is as follows: i = ten i = 32 Then, running the program in Release version mode, the output is as follows: i = ten i = 10 output results show that the compiler optimized the code in release mode, and the second time no output The correct I value. Below, we add the declaration of I to the volatile keyword to see what happens: #i nclude <stdio.h> void Main () {volatile int i=10; int a = i; printf ("I=%d", a) ; __asm {mov dword ptr [ebp-4],20h} int b = i; printf ("i=%d", b); Run in Debug and release versions, respectivelyprogram, output are: i = ten i = 32 This indicates that this keyword has played its role. ------------------------------------volatile the corresponding variable may be changed in your program itself do not know the circumstances of the change, such as multithreaded programs, common access to the memory, multiple programs can manipulate this variable your own program, It's impossible to determine when this variable will change. For example, he corresponds to a certain state of an external device, and when an external device occurs, the system changes the value of the variable by the driver and the interrupt event, and your program does not know. For the volatile type of variable, each time the system uses it is directly extracted from the corresponding memory, and will not take advantage of the original cache value, in order to adapt to its unknown when the changes will occur, the system will not do to optimize the processing of such variables- Obviously also because its value can change at any time. --------------------------------------------------------------------------------Typical example for (int i=0; i<100000; i+ +); This statement is used to test the speed of the empty loop, but the compiler is sure to tune it out and not execute if you write for (volatile int i=0; i<100000; i++); It's going to execute volatile. "Variable" because the speed of the access registers is faster than RAM, the compiler generally makes optimizations to reduce access to external RAM. For example: static int i=0; int main (void) {... while⑴{if (i) dosomething ();}}/* Interrupt service routine. /void isr_2 (void) {I=1} The intention of the program is to invoke the DoSomething function in main when the isr_2 interrupt is generated, however, since the compiler determines that I is not modified in the main function, it is possible to perform only once to a Registers read operation, and then each if judgment only uses "I copy" inside this register, cause dosomething will never be called. If you add a variable to the volatile modifier, the compiler guarantees that the read-write operation on this variable will not be optimized (definitely executed). I should also say so in this example. use of localGenerally speaking, volatile is used in several places as follows: 1, the variable which is modified in the Interrupt Service program for other program detection needs to add volatile; 2, the symbol sharing between tasks in a multitasking environment should be added to the volatile; 3. Memory-mapped hardware registers are usually added with volatile instructions, because each read and write to it may have a different meaning, and, in addition, these situations often have to consider the integrity of the data (the correlation of several flags read half was interrupted rewrite), in 1 can be implemented by the turn-off interrupt, 2 can prohibit task scheduling, 3 only rely on the good hardware design.

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.