Why volatile variable used in c




















Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port:. Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop.

That one will be optimized out. The compiler will try to be clever, read the value of isBusy just once and then go into an infinite loop. That's not what you want. The way to get around this is to declare the pointer gadget as volatile. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either. It will tell the compiler not to cache the value of this variable.

So it will generate code to take the value of the given volatile variable from the main memory every time it encounters it. This mechanism is used because at any time the value can be modified by the OS or any interrupt. So using volatile will help us accessing the value afresh every time. The compiler is allowed to notice the loop body does not touch the quit variable and convert the loop to a while true loop.

However, if the quit variable is declared volatile , the compiler is forced to load it every time, because it can be modified elsewhere. This is exactly what you want in this situation. If this is not specified in such cases, some variable accesses can be optimised, e.

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. So when dealing with some memory locations e. The first two rules ensure proper reading and writing. 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.

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. That's the use case for volatile. A marginal use for volatile is the following. Say you want to compute the numerical derivative of a function f :. Think about it : when you substract very close numbers, you lose a lot of significant digits which can ruin the computation of the derivative think 1.

A possible workaround could be. So you write instead. Compiler will not optimise the functions that uses variables that are defined with volatile keyword. This is used more often to control memory-mapped devices, access CPU registers and locate specific memory locations. See examples with assembly listing. If you access the memory-mapped file's data through pointers to non-volatile objects at the source code level , then the code generated by the compiler can fetch the same data multiple times without you being aware of it.

If that data happens to change, your program may become using two or more different versions of the data and get into an inconsistent state. This can lead not only to logically incorrect behavior of the program but also to exploitable security holes in it if it processes untrusted files or files from untrusted locations.

Volatile is also useful, when you want to force the compiler not to optimize a specific code sequence e. This means that if you reference the variable, the program should always check the physical address ie a mapped input fifo , and not use it in a cached way. In the language designed by Dennis Ritchie, every access to any object, other than automatic objects whose address had not been taken, would behave as though it computed the address of the object and then read or wrote the storage at that address.

This made the language very powerful, but severely limited optimization opportunities. While it might have been possible to add a qualifier that would invite a compiler to assume that a particular object wouldn't be changed in weird ways, such an assumption would be appropriate for the vast majority of objects in C programs, and it would have been impractical to add a qualifier to all the objects for which such assumption would be appropriate.

On the other hand, some programs need to use some objects for which such an assumption would not hold. To resolve this issue, the Standard says that compilers may assume that objects which are not declared volatile will not have their value observed or changed in ways that are outside the compiler's control, or would be outside a reasonable compiler's understanding.

Because various platforms may have different ways in which objects could be observed or modified outside a compiler's control, it is appropriate that quality compilers for those platforms should differ in their exact handling of volatile semantics.

In my opinion, you should not expect too much from volatile. To illustrate, look at the example in Nils Pipenbrinck's highly-voted answer. I would say, his example is not suitable for volatile.

It is nothing about the thread safe, atomic access or even memory order. At running time, the processor still possibly reorders the data and command assignment, regarding to the processor architecture. The memory barrier is needed between data and command assignment. Volatile in C programming language is a keyword which is used with variables to inform the compiler not to apply any optimizations to code dealing with the variable.

This is used to avoid some assumptions that go into compiler optimizations which can break the code. This is mainly used in Embedded Systems programming and real time systems. As a general rule, all variables whose value can change suddenly due to an external reason like an external device or another program thread should be declared using volatile.

Note that unnecessarily using volatile for all keywords will reduce performance and not using it when required will result in unexpected execution result.

We will see how the efficiency of the code changes when we use volatile and how quickly we can apply this functionality in our code.

Volatile is used in C programming when we need to go and read the value stored by the pointer at the address pointed by the pointer. If you need to change anything in your code that is out of compiler reach you can use this volatile keyword before the variable for which you want to change the value. Explanation: In the above code, we have declared an integer variable with value 0 assigned to it.

Then in the main class, we have set the if condition which will hold true until and unless the value of variable a is 0. But things will change when we will add keyword volatile to the declaration of integer variable a.

Explanation: In the above code, we have declared a volatile integer variable a. Then in the main class, we have set two things one is the value of integer variable is 0 and second is the if condition which will hold true until and unless the value of variable a is 0. As you can see the output will always be 0 as the condition will always remain true because the variable is declared as volatile.

So the compiler will know that the variable can change anytime. In addition, we are printing the old value then we are printing the modified value on the screen. This modification is possible only because of the volatile keyword we have used in the declaration of the variable.



0コメント

  • 1000 / 1000