Volatile (computer programming): Difference between revisions

Content deleted Content added
Cleaning up a typo
Fixing more typos
Line 3:
In [[computer programming]], a '''volatile''' [[Value (computer science)|value]] is a value that can be read by something else or changed by something else while the current code is running.
 
Despite being a common keyword across many programming languages, the behavior of the <code>volatile</code> keyword differs in subtle and important ways between different programming languages. The common theme is that a <code>volatile</code> variable is a variable that may be read or modified by something outside of the current [[thread (computing)|thread of execution]] while the current [[thread (computing)|thread]] is running. In particular, the value of a <code>volatile</code> variable may appear change spontaneously without any apparent cause from the code in the [[thread (computing)|thread]] and sometimes without any apparent cause from any code in the whole program. The typical things that can read or modify <code>Volatilevolatile</code> variables include hardware devices via [[memory-mapped I/O]] (where reading from or writing to memory is used to communicate with [[peripheral device]]s), asynchronous signal handlers, and other [[thread (computing)|threads of execution]], but not all programming languages use the <code>volatile</code> keyword for all of these examples.
 
Volatility can have implications regarding function [[calling convention]]s and how variables are stored, accessed and cached.
Line 16:
*Allow access to [[memory-mapped I/O]] devices.
*Allow preserving values across a <code>[[setjmp|longjmp]]</code>.
*Allow sharing values between signal handlers and the rest of the program in in <code>volatile</code> <code>sig_atomic_t</code> objects.
 
The C and C++ standards allow writing portable code that shares values across a <code>[[setjmp|longjmp]]</code> in <code>volatile</code> objects, and the standards allow writing portable code that shares values between signal handlers and the rest of the code in <code>volatile</code> <code>sig_atomic_t</code> objects. Any other use of <code>volatile</code> keyword in C and C++ is inherently non-portable or incorrect. In particular, writing code with the <code>volatile</code> keyword for [[memory-mapped I/O]] devices is inherently non-portable and always requires deep knowledge of the specific target C/C++ implementation and platform.