Why is volatile needed in C?

前端 未结 18 2219
攒了一身酷
攒了一身酷 2020-11-22 04:07

Why is volatile needed in C? What is it used for? What will it do?

相关标签:
18条回答
  • 2020-11-22 04:26

    A volatile can be changed from outside the compiled code (for example, a program may map a volatile variable to a memory mapped register.) The compiler won't apply certain optimizations to code that handles a volatile variable - for example, it won't load it into a register without writing it to memory. This is important when dealing with hardware registers.

    0 讨论(0)
  • 2020-11-22 04:27

    There are two uses. These are specially used more often in embedded development.

    1. Compiler will not optimise the functions that uses variables that are defined with volatile keyword

    2. Volatile is used to access exact memory locations in RAM, ROM, etc... This is used more often to control memory-mapped devices, access CPU registers and locate specific memory locations.

    See examples with assembly listing. Re: Usage of C "volatile" Keyword in Embedded Development

    0 讨论(0)
  • 2020-11-22 04:27

    As rightly suggested by many here, the volatile keyword's popular use is to skip the optimisation of the volatile variable.

    The best advantage that comes to mind, and worth mentioning after reading about volatile is -- to prevent rolling back of the variable in case of a longjmp. A non-local jump.

    What does this mean?

    It simply means that the last value will be retained after you do stack unwinding, to return to some previous stack frame; typically in case of some erroneous scenario.

    Since it'd be out of scope of this question, I am not going into details of setjmp/longjmp here, but it's worth reading about it; and how the volatility feature can be used to retain the last value.

    0 讨论(0)
  • 2020-11-22 04:28

    volatile tells the compiler that your variable may be changed by other means, than the code that is accessing it. e.g., it may be a I/O-mapped memory location. If this is not specified in such cases, some variable accesses can be optimised, e.g., its contents can be held in a register, and the memory location not read back in again.

    0 讨论(0)
  • 2020-11-22 04:28

    My simple explanation is:

    In some scenarios, based on the logic or code, the compiler will do optimisation of variables which it thinks do not change. The volatile keyword prevents a variable being optimised.

    For example:

    bool usb_interface_flag = 0;
    while(usb_interface_flag == 0)
    {
        // execute logic for the scenario where the USB isn't connected 
    }
    

    From the above code, the compiler may think usb_interface_flag is defined as 0, and that in the while loop it will be zero forever. After optimisation, the compiler will treat it as while(true) all the time, resulting in an infinite loop.

    To avoid these kinds of scenarios, we declare the flag as volatile, we are telling to compiler that this value may be changed by an external interface or other module of program, i.e., please don't optimise it. That's the use case for volatile.

    0 讨论(0)
  • 2020-11-22 04:30

    See this article by Andrei Alexandrescu, "volatile - Multithreaded Programmer's Best Friend"

    The volatile keyword was devised to prevent compiler optimizations that might render code incorrect in the presence of certain asynchronous events. For example, if you declare a primitive variable as volatile, the compiler is not permitted to cache it in a register -- a common optimization that would be disastrous if that variable were shared among multiple threads. So the general rule is, if you have variables of primitive type that must be shared among multiple threads, declare those variables volatile. But you can actually do a lot more with this keyword: you can use it to catch code that is not thread safe, and you can do so at compile time. This article shows how it is done; the solution involves a simple smart pointer that also makes it easy to serialize critical sections of code.

    The article applies to both C and C++.

    Also see the article "C++ and the Perils of Double-Checked Locking" by Scott Meyers and Andrei Alexandrescu:

    So when dealing with some memory locations (e.g. memory mapped ports or memory referenced by ISRs [ Interrupt Service Routines ] ), some optimizations must be suspended. volatile exists for specifying special treatment for such locations, specifically: (1) the content of a volatile variable is "unstable" (can change by means unknown to the compiler), (2) all writes to volatile data are "observable" so they must be executed religiously, and (3) all operations on volatile data are executed in the sequence in which they appear in the source code. The first two rules ensure proper reading and writing. The last one allows implementation of I/O protocols that mix input and output. This is informally what C and C++'s volatile guarantees.

    0 讨论(0)
提交回复
热议问题