Volatile keywords in c language

Source: Internet
Author: User

To talk about my understanding and summary of the volatile keyword, volatile keyword is a C language is not commonly used in a keyword, it is estimated that many people have not heard, our project because of multithreaded design is also used in the volatile keyword, hereby summed up:

1, first of all say compiler optimization.

int i=5;
int a=i;
......
int b=i;

The compiler will put I in the register, and B will take the value directly from the register. The compiler does such optimizations to be quick. But there is a problem, once I was in the memory changed, this is not the result of the error, so in order to avoid compiler optimization error results, volatile keyword can be used to declare I.

2, the application scene, I can use the scenario is that in multi-threaded situations, if a variable is often changed, it is necessary to declare it as volatile type.

3, the typical interview question, as follows:

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


So the statement is wrong, because the record that PTR points to may have changed, then it is not squared.

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

(End of this 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.