The meaning of keyword volatile in C language "go"

Source: Internet
Author: User
Tags volatile

This article reproduced from: http://m.jb51.net/article/37489.htm This article is the C language keyword volatile meaning of the detailed analysis introduced, the need for a friend to refer to the volatile meaning is "volatile, easy to change." The meaning of this qualifier is to indicate to the compiler that the contents of a variable may change due to modifications by other programs. Usually when a variable is declared in a program, the compiler tries to store it in a common register, such as EBX. When the CPU puts its value into 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 point, the value in EBX is not updated with it. To resolve this situation, a volatile qualifier is created so that the code must obtain its value from the specified location when referencing the variable.

What does the keyword volatile mean? and gives three different examples. A variable that is defined as volatile means that the variable may be unexpectedly changed so that the compiler does not assume the value of the variable. Precisely, the optimizer must carefully re-read the value of the variable each time it uses the variable, rather than using the 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 variables that are accessed in an interrupt service subroutine (non-automatic variables)
3). Variables shared by several tasks in multi-threaded applications
The person who cannot answer the question will not be hired. I think this is the most basic problem of distinguishing 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 that the interviewee answered the question correctly (well, wondering if this would be the case), I'll look at it a little bit and see if this guy knows exactly the importance of volatile.
1). Can a parameter be either const or volatile? explain why.
2). Can a pointer be volatile? explain why.
3). What is wrong with the following function:
int square (volatile int *ptr)
{return *ptr * *PTR;}
Here's 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 service subroutine fixes a pointer that points 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:

int square (volatile int *ptr)
{
int A, B;
A = *ptr;
b = *ptr;
return a * b;
}
Because the values of the *ptr can be unexpectedly changed, A and B may be different. As a result, this code may return to the square value you expect! The correct code is as follows:

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


volatile is meant to be "variable."
Because the access register is faster than RAM, the compiler generally makes optimizations to reduce access to external RAM. Like what:

static int i=0;
int main (void)
{
...
while (1)
{
if (i) dosomething ();
}
}
/* Interrupt Service routine. */
void isr_2 (void)
{
I=1;
}
The intent 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 is not modified in the main function,
It is possible to perform only one read operation from I to a register, and then each time the if judge uses only the "I copy" inside the register, causing the dosomething to never be called. If you add a volatile modifier to a variable, the compiler guarantees that read and write operations on this variable will not be optimized (definitely executed). I should also explain this in this example.
generally, volatile is used in several places:
1, the change in the Interrupt service program for other programs to detect variables need to add volatile;
2, multi-tasking environment to share the logo should be added volatile;
3, Memory mapping hardware register usually also add volatile description, because each time it read and write may be different meanings;
In addition, these situations often need to consider the integrity of the data at the same time (the correlation of several flags read half interrupted rewrite), in 1 can be closed by the interrupt to real
Now, 2 can prohibit task scheduling, 3 can only rely on the good hardware design.
//=============
The pointer type is also a variable, so it can be modified with volatile.
The volatile keyword is a type modifier that declares a type variable that can be changed by factors that are unknown to some compilers, such as
Operating system, hardware, or other threads. A variable that is declared by this keyword is encountered by the compiler, and the code that accesses the variable is no longer
Optimized to provide stable access to special addresses.
examples of using this keyword are:
int volatile nvint;
When a variable declared with a volatile value is required, the system always re-reads the data from its memory, even if it precedes the reference
The data has just been read from that point. And the read data is saved immediately.
For example:
volatile int i=10;
int a = i;
。。。 Other code does not explicitly tell the compiler that I have been manipulated
int b = i;
Volatile indicates that I is subject to change at any time and must be read from the address of I each time it is used, so the compiler generates
The assembly code will re-read the data from I's address in B. While the optimization procedure is, because the compiler discovers two times from the I read the data between the code
Code does not operate on I, it automatically places the last-read data in B. Instead of re-reading from inside I. So since, if
I is a register variable or a port data is error prone, so volatile can guarantee a stable access to the special address.
Note that in VC6, the General debug mode is not optimized for code, so the function of this keyword is not visible. below by inserting assembly
Code to test for the effect of a volatile keyword 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:

#include <stdio.h>
void Main ()
{
int i=10;
int a = i;
printf ("I=%d\n", a);
The function of the following assembly statement is to change the value of I in memory, but it does not let the compiler know
__asm {
mov dword ptr [ebp-4], 20h
}
int b = i;
printf ("I=%d\n", b);
}
Then, running the program in debug version mode, the output is as follows:

i = 10
i = 32
Then, running the program in Release version mode, the output is as follows:

i = 10
i = 10
The results of the output clearly indicate that the compiler optimized the code in release mode and did not output the correct I value for the second time.
Next, let's add the I statement to the volatile keyword to see what's changed:

#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 in debug and release versions, respectively, with the output:

i = 10
i = 32 This indicates that the keyword has played its part!

The meaning of keyword volatile in C language "go"

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.