On the meaning of keyword volatile in C language _c language

Source: Internet
Author: User
Tags volatile
The meaning of volatile is "volatile, easy to change". The meaning of this qualifier is to indicate to the compiler that the contents of a variable may change as a result of another program's modification. Usually when a variable is declared in a program, the compiler tries to store it in a general-purpose register, such as EBX. When the CPU puts its value in the EBX, it will no longer care about the value in the corresponding memory. If another program (such as a kernel program or an interrupt) modifies its value in memory at this time, the value in EBX will not be updated. To resolve this situation, the volatile qualifier is created so that the code must get its value from the specified location when referencing the variable.

What is the meaning of the keyword volatile? And give three different examples. A variable defined as volatile means 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). Non-automatic variable (non-automatic variables) that is accessed in an interrupt service subroutine
3. Variables shared by several tasks in multi-threaded applications
A person who cannot answer this question will not 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, which require 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 is straight and 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). What's wrong with the following function:
int square (volatile int *ptr)
{return *ptr * *PTR;}
here 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 a medium service subroutine fixes the pointer to a buffer.
3. There's a prank on this piece of code. The purpose of this code is to return the 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:
Copy Code code as follows:

int square (volatile int *ptr)
{
int a,b;
A = *ptr;
b = *ptr;
return a * b;
}

Because the value of the *ptr can be unexpectedly changed, A and B may be different. As a result, this code may not return the square value you expected! The correct code is as follows:
Copy Code code as follows:

Long Square (volatile int *ptr)
{
int A;
A = *ptr;
Return a * A; }


volatile was meant to be "variable."
Because the speed of access registers is faster than RAM, the compiler generally makes optimizations to reduce access to external RAM. Like what:
Copy Code code as follows:

static int i=0;
int main (void)
{
...
while (1)
{
if (i) dosomething ();
}
}
/* Interrupt Service routine. */
void isr_2 (void)
{
I=1;
}

The intention of the program is to call the DoSomething function in main when the isr_2 interrupt is generated, but because the compiler determines that I has not been modified in the main function,
It is possible to perform only one read operation from I to a register, and then each if judgment only uses the "I copy" of the Register, causing DoSomething to never be invoked. If you add volatile to the variable, 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.
Generally speaking, volatile is used in several places as follows:
1, the interruption of the service program for other procedures to detect the variables need to add volatile;
2. The volatile should be added to the signs shared between tasks in a multitasking environment;
3, memory mapping hardware registers are usually added volatile description, because each of its reading and writing may be different meaning;
In addition, these situations often have to take into account the integrity of the data (a number of interrelated flags read half of the interrupted rewrite), in 1 can be broken to real
Now, 2 can prohibit task scheduling, 3 only rely on the good hardware design.
//=============
The pointer type is also a variable, so it can be decorated with volatile.
The volatile keyword is a type modifier that declares a type variable that can be changed by factors unknown to some compilers, such as
Operating system, hardware, or other threads. When you encounter a variable of this keyword declaration, the compiler does not perform the code that accesses the variable
Optimized to provide stable access to special addresses.
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 the memory it is in, even if the preceding reference
The data has just been read from here. And the data being read is saved immediately.
For example:
volatile int i=10;
int a = i;
。。。 Other code that does not explicitly tell the compiler that the I has been manipulated
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 I use it, so the compiler generates
The assembly code will again read the data from the address of I and put it in B. The optimization approach is that, because the compiler finds two times between the code that reads data from I
Code does not operate on I, it automatically places the last read data in B. Rather than re reading from I. So since, if
I is a register variable or a port data is prone to error, so that 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. Below by inserting the Assembly
Code, test for volatile keyword, impact on program final code:
First use ClassWizard to build a Win32 console project, insert a voltest.cpp file, and enter the following code:
Copy Code code as follows:

#include <stdio.h>
void Main ()
{
int i=10;
int a = i;
printf ("I=%d\n", a);
The purpose of the following assembly 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\n", b);
}

Then, run the program in debug version mode, and the output is as follows:
Copy Code code as follows:

i = 10
i = 32

Then, run the program in Release version mode, and the output is as follows:
Copy Code code as follows:

i = 10
i = 10

The results of the output show that, in release mode, the compiler optimizes the code and does not output the correct I value for the second time.
Below, we add the declaration of I to the volatile keyword to see what changes:
Copy Code code as follows:

#include <stdio.h>
void Main ()
{
volatile int i=10;
int a = i;
printf ("I=%d\n", a);
__asm {
mov dword ptr [ebp-4], 20h
}
int b = i;
printf ("I=%d\n", b);
}

Run the program separately in the debug and release versions, and the output is:
Copy Code code as follows:

i = 10
i = 32
This shows that the keyword has played its role!

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.