Why is volatile
needed in C? What is it used for? What will it do?
Why is volatile needed in C
cdeclarationvolatile
Related Topic
- C++ – Why use apparently meaningless do-while and if-else statements in macros
- C# – Volatile vs. Interlocked vs. lock
- C++ – the effect of extern “C” in C++
- Sqlite – Improve INSERT-per-second performance of SQLite
- Java – Volatile boolean vs AtomicBoolean
- What does the ??!??! operator do in C
- Java – the difference between atomic / volatile / synchronized
Best Answer
volatile
tells the compiler not to optimize anything that has to do with thevolatile
variable.There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code: When you interface with hardware that changes the value itself; when there's another thread running that also uses the variable; or when there's a signal handler that might change the value of the variable.
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:
Now you want to send some command:
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
asvolatile
. 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 eitherThis is the correct version: