volatile Volatile object qualifier

volatile Volatile object qualifier

volatile suits device registers. Signal-handler sharing requires volatile sig_atomic_t, not any volatile object. It gives no atomicity or synchronization.

CategoryType qualifiers
KindKeyword / Statement
C standardC89 / C90

📝 Syntax

volatile int flag;

▶ Example

Edit the C code below and click Run; the server compiles and executes it:

Output:

status = 1, attempts = 1
ℹ️ Info The original unbounded wait is now a bounded loop: update_status sets status to 1 on the first pass, so attempts is always 1. This function only simulates a status update; it does not present volatile as real thread synchronization.

📚 Related Tutorials

❓ FAQ

QCan volatile replace atomic operations for thread safety?
ANo. volatile provides no atomic read-modify-write, mutual exclusion, or inter-thread happens-before relationship. Shared mutable state should use C11 atomics with suitable memory ordering, or mutexes.
QDoes volatile prevent the compiler from performing all optimizations?
ANo. It constrains accesses to volatile objects so that they actually occur and are ordered as required by the abstract machine; other computations can still be optimized. It does not mandate a particular CPU cache instruction for every access.
QCan the volatile flag-waiting example hang forever?
ANo. The loop attempts at most three passes, and update_status writes 1 on the first, making the condition false. Real hardware polling should still include a timeout and use the platform's prescribed register-access method.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏