ArticleslgStudy

computer science

Volatile (computer programming)

Volatile (computer programming) is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Volatile (computer programming) rather than just read about it. In short: In computer programming, a variable is said to be volatile if its value can be read or modified asynchronously by something other than the current thread of execution. The value of a volatile variable may spontaneously change for reasons such as: sharing values with other threads; sharing values with asynchronous signal handlers; accessing hardware devices via memory-mapped I/O (where messages from peripheral device…

Key takeaways

  • Volatile (computer programming) belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Volatile (computer programming) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Volatile (computer programming) from memory before moving on to harder problems.

Reference excerpt

In computer programming, a variable is said to be volatile if its value can be read or modified asynchronously by something other than the current thread of execution. The value of a volatile variable may spontaneously change for reasons such as: sharing values with other threads; sharing values with asynchronous signal handlers; accessing hardware devices via memory-mapped I/O (where messages from peripheral devices can be received and sent by reading from and writing to memory). Support for these use cases varies considerably among the programming languages that have the volatile keyword. Volatility can have implications regarding function calling conventions and how variables are stored, accessed and cached.

In C and C++ In C and C++, volatile is a type qualifier, like const, and is a part of a type (e.g. the type of a variable or field). The behavior of the volatile keyword in C and C++ is sometimes given in terms of suppressing optimizations of an optimizing compiler: 1- don't remove existing volatile reads and writes, 2- don't add new volatile reads and writes, and 3- don't reorder volatile reads and writes. However, this definition is only an approximation for the benefit of new learners, and this approximate definition should not be relied upon to write real production code. In C, and consequently C++, the volatile keyword was intended to:

Allow access to memory-mapped I/O devices. Allow preserving values across a longjmp. Allow sharing values between signal handlers and the rest of the program in volatile sig_atomic_t objects. The C and C++ standards allow writing portable code that shares values across a longjmp in volatile objects, and the standards allow writing portable code that shares values between signal handlers and the rest of the code in volatile sig_atomic_t objects. Any other use of volatile keyword in C and C++ is inherently non-portable or incorrect. In particular, writing code with the volatile 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.

Multi-threading It is a common misconception that the volatile keyword is useful in portable multi-threading code in C and C++. The volatile keyword in C and C++ has never functioned as a useful, portable tool for any multi-threading scenario. Unlike the Java and C# programming languages, operations on volatile variables in C and C++ are not atomic, and operations on volatile variables do not have sufficient memory ordering guarantees (i.e. memory barriers). Most C and C++ compilers, linkers, and runtimes simply do not provide the necessary memory ordering guarantees to make the volatile keyword useful for any multi-threading scenario. Before the C11 and C++11 standards, programmers were forced to rely on guarantees from the individual implementations and platforms (e.g. POSIX and WIN32) to write multi-threading code. With the modern C11 and C++11 standards, programmers can write portable multi-threading code using new portable constructs such as the std::atomic<T> templates.

Example of memory-mapped I/O in C In this example, the code sets the value stored in foo to 0. It then starts to poll that value repeatedly until it changes to 255:

An optimizing compiler will notice that no other code can possibly change the value stored in foo, and will assume that it will remain equal to 0 at all times. The compiler will therefore replace the function body with an infinite loop similar to this:

However, the programmer may make foo refer to another element of the computer system such as a hardware register of a device connected to the CPU which may change the value of foo while this code is running. (This example does not include the details on how to make foo refer to a hardware register of a device connected to the CPU.) Without the volatile keyword, an optimizing compiler will likely convert the code from the first sample with the read in the loop to the second sample without the read in the loop as part of the common loop-invariant code-motion optimization, and thus the code will likely never notice the change that it is waiting for. To prevent the compiler from doing this optimization, the volatile keyword can be used:

The volatile keyword prevents the compiler from moving the read out of the loop, and thus the code will notice the expected change to the variable foo.

Optimization comparison in C The following C programs, and accompanying assembler language excerpts, demonstrate how the volatile keyword affects the compiler's output. The compiler in this case was GCC. While observing the assembly code, it is clearly visible that the code generated with volatile objects is more verbose, making it longer so the nature of volatile objects can be fulfilled. The volatile keyword prevents the compiler from performing optimization on code involving volatile objects, thus ensuring that each volatile variable assignment and read has a corresponding memory access. Without the volatile keyword, the compiler knows a variable does not need to be reread from memory at each use, because there should not be any writes to its memory location from any other thread or process.

Compiler defects Unlike other language features of C and C++, the volatile keyword is not well supported by most C/C++ implementations - even for portable uses according to the C and C++ standards. Most C/C++ implementations are buggy regarding the behavior of the volatile keyword. Programmers should take great care whenever using the volatile keyword in C and C++.

In Java In all modern versions of the Java programming language, the volatile keyword gives the following guarantees:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Volatile (computer programming)

Start with the simplest possible case. Write down what Volatile (computer programming) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Volatile (computer programming) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Volatile (computer programming) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Volatile (computer programming)

In research
Volatile (computer programming) appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Volatile (computer programming) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Volatile (computer programming) is common in secondary-school and first-year university syllabi. It links to neighbouring topics C (programming language), Concurrency control, Variable (computer science), so understanding it makes those chapters shorter.
In everyday life
Look for Volatile (computer programming) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Volatile (computer programming)” →

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Volatile (computer programming) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Volatile (computer programming) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Volatile (computer programming) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Volatile (computer programming) in simple terms?

In computer programming, a variable is said to be volatile if its value can be read or modified asynchronously by something other than the current thread of execution. The value of a volatile variable may spontaneously change for reasons such as: sharing values with other threads; sharing values wi…

Why does Volatile (computer programming) matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Volatile (computer programming)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Volatile (computer programming).

Tags

  • C (programming language)
  • Concurrency control
  • Variable (computer science)

Keep exploring