Table of Contents
What does volatile do exactly?
When should you use volatile?
How is volatile different from const?
Some gotchas with volatile
Home Backend Development C++ What is the volatile keyword in C ?

What is the volatile keyword in C ?

Jul 04, 2025 am 01:09 AM
c++ volatile

volatile tells the compiler that the value of the variable may change at any time, preventing the compiler from optimizing access. 1. Used for hardware registers, signal handlers, or shared variables between threads (but modern C recommends std::atomic). 2. Each access is directly read and write memory instead of cached to registers. 3. It does not provide atomicity or thread safety, and only ensures that the compiler does not optimize read and write. 4. Constantly, the two are sometimes used in combination to represent read-only but externally modifyable variables. 5. It cannot replace mutexes or atomic operations, and excessive use will affect performance.

What is the volatile keyword in C?

The volatile keyword in C is used to tell the compiler that a variable's value can change at any time — even outside the current code flow. This means the compiler should not optimize accesses to that variable, because doing so could lead to incorrect behavior.

What is the volatile keyword in C?

You typically see volatile used when dealing with hardware registers, signal handlers, or variables shared between threads (though for the latter, modern C offers better tools like std::atomic ).

What is the volatile keyword in C?

What does volatile do exactly?

When you declare a variable as volatile , the compiler assumes that any read or write to that variable must actually happen — it can't be cached in a register or reordered for optimization purposes. So every access goes directly to memory.

For example:

What is the volatile keyword in C?
 volatile int status_flag;

Here, every time status_flag is accessed, the program will read its actual value from memory instead of assuming what it might be based on previous operations.

This helps prevent bugs in scenarios like:

  • Memory-mapped I/O where hardware changes values ​​behind the scenes.
  • Variables modified by an interrupt service routine.
  • Shared memory in certain low-level concurrency situations (though again, prefer std::atomic these days).

When should you use volatile?

Use volatile when working with:

  • Hardware registers – such as those in embedded systems where memory-mapped devices update values ​​independently.
  • Memory shared with other threads or processes without using synchronization primitives — though this is tricky and often not sufficient on its own.
  • Signal handlers – if a variable is changed inside a signal handler and used elsewhere in the program.

Keep in mind: volatile does not provide atomicity or thread safety. It only ensures that the compiler doesn't optimize away reads and writes.

So if you're writing multithreaded code, prefer types like std::atomic<T> over volatile .


How is volatile different from const?

While const tells the compiler a variable shouldn't change, volatile says the opposite — that it might change at any time. Sometimes you'll even see both together:

 volatile const int sensor_value;

This would be used for something like a read-only hardware register whose value changes on its own.

Also, note that const volatile combinations are more common in device drivers or real-time systems where a value is meant to be read-only from the program's perspective but still subject to external updates.


Some gotchas with volatile

  • It doesn't replace mutexes or atomics. If two threads modify a volatile variable without synchronization, you still get a race condition.
  • It doesn't stop all optimizations. It prevents caching in registers and some reorderings, but not all concurrency-related issues.
  • Misuse can hurt performance. Since the compiler can't optimize access to volatile variables, excessive use may slow your code down unnecessarily.

So basically, use volatile when you need to interact with memory that can be updated asynchronously — but don't expect it to handle synchronization or thread safety for you.

Basically that's it.

The above is the detailed content of What is the volatile keyword in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Understanding move assignment operator in C Understanding move assignment operator in C Jul 16, 2025 am 02:20 AM

ThemoveassignmentoperatorinC isaspecialmemberfunctionthatefficientlytransfersresourcesfromatemporaryobjecttoanexistingone.ItisdefinedasMyClass&operator=(MyClass&&other)noexcept;,takinganon-constrvaluereferencetoallowmodificationofthesour

Object Slicing in C Object Slicing in C Jul 17, 2025 am 02:19 AM

Object slice refers to the phenomenon that only part of the base class data is copied when assigning or passing a derived class object to a base class object, resulting in the loss of new members of the derived class. 1. Object slices occur in containers that directly assign values, pass parameters by value, or store polymorphic objects in storage base classes; 2. The consequences include data loss, abnormal behavior and difficult to debug; 3. Avoiding methods include passing polymorphic objects using pointers or references, or using smart pointers to manage the object life cycle.

Explain RAII in C Explain RAII in C Jul 22, 2025 am 03:27 AM

RAII is an important technology used in resource management in C. Its core lies in automatically managing resources through the object life cycle. Its core idea is: resources are acquired at construction time and released at destruction, thereby avoiding leakage problems caused by manual release. For example, when there is no RAII, the file operation requires manually calling fclose. If there is an error in the middle or return in advance, you may forget to close the file; and after using RAII, such as the FileHandle class encapsulates the file operation, the destructor will be automatically called after leaving the scope to release the resource. 1.RAII is used in lock management (such as std::lock_guard), 2. Memory management (such as std::unique_ptr), 3. Database and network connection management, etc.

C   Initialization techniques C Initialization techniques Jul 18, 2025 am 04:13 AM

There are many initialization methods in C, which are suitable for different scenarios. 1. Basic variable initialization includes assignment initialization (inta=5;), construction initialization (inta(5);) and list initialization (inta{5};), where list initialization is more stringent and recommended; 2. Class member initialization can be assigned through constructor body or member initialization list (MyClass(intval):x(val){}), which is more efficient and suitable for const and reference members. C 11 also supports direct initialization within the class; 3. Array and container initialization can be used in traditional mode or C 11's std::array and std::vector, support list initialization and improve security; 4. Default initialization

What is high-frequency virtual currency trading? The principles and technical implementation points of high-frequency trading What is high-frequency virtual currency trading? The principles and technical implementation points of high-frequency trading Jul 23, 2025 pm 11:57 PM

High-frequency trading is one of the most technologically-rich and capital-intensive areas in the virtual currency market. It is a competition about speed, algorithms and cutting-edge technology that ordinary market participants are hard to get involved. Understanding how it works will help us to have a deeper understanding of the complexity and specialization of the current digital asset market. For most people, it is more important to recognize and understand this phenomenon than to try it yourself.

Standard Template Library (STL) in C Standard Template Library (STL) in C Jul 16, 2025 am 01:07 AM

C STL improves code efficiency through containers, algorithms and iterators. 1. The container includes vector (dynamic array, suitable for tail insertion and deletion), list (bidirectional linked list, suitable for frequent intermediate insertion and deletion), map and set (based on red and black trees, automatic sorting and searching fast). When choosing, consider the use scenario and time complexity; 2. Algorithms such as sort(), find(), copy(), etc. operate the data range through iterators to improve universality and security. When using it, pay attention to whether the original data is modified and the iterator's validity; 3. Function objects and lambda expressions can be used for custom operations. lambdas are suitable for simple logic, and function objects are suitable for multiplexing or complex logic. At the same time, pay attention to capturing the list to avoid dangling references. Palm

C   bitwise operators explained C bitwise operators explained Jul 18, 2025 am 03:52 AM

The bit operator in C is used to directly operate binary bits of integers, and is suitable for systems programming, embedded development, algorithm optimization and other fields. 1. Common bit operators include bitwise and (&), bitwise or (|), bitwise XOR (^), bitwise inverse (~), and left shift (). 2. Use scenario stateful flag management, mask operation, performance optimization, and encryption/compression algorithms. 3. Notes include distinguishing bit operations from logical operations, avoiding unsafe right shifts to signed numbers, and not overuse affecting readability. It is also recommended to use macros or constants to improve code clarity, pay attention to operation order, and verify behavior through tests.

What is a destructor in C  ? What is a destructor in C ? Jul 19, 2025 am 03:15 AM

The destructor in C is a special member function that is automatically called when an object is out of scope or is explicitly deleted. Its main purpose is to clean up resources that an object may acquire during its life cycle, such as memory, file handles, or network connections. The destructor is automatically called in the following cases: when a local variable leaves scope, when a delete is called on the pointer, and when an external object containing the object is destructed. When defining the destructor, you need to add ~ before the class name, and there are no parameters and return values. If undefined, the compiler generates a default destructor, but does not handle dynamic memory releases. Notes include: Each class can only have one destructor and does not support overloading; it is recommended to set the destructor of the inherited class to virtual; the destructor of the derived class will be executed first and then automatically called.

See all articles