Alex Rivera | Logout

Why does volatile exist?

Asked 2008-09-16T13:59:45.667
295

What does the volatile keyword do? In C++ what problem does it solve?

In my case, I have never knowingly needed it.

Edit
Report

2 Answers

21

You MUST use volatile when implementing lock-free data structures. Otherwise the compiler is free to optimize access to the variable, which will change the semantics.

To put it another way, volatile tells the compiler that accesses to this variable must correspond to a physical memory read/write operation.

For example, this is how InterlockedIncrement is declared in the Win32 API:

LONG __cdecl InterlockedIncrement(
  __inout  LONG volatile *Addend
);
answered 2008-09-17T11:55:18.687
5
  1. you must use it to implement spinlocks as well as some (all?) lock-free data structures
  2. use it with atomic operations/instructions
  3. helped me once to overcome compiler's bug (wrongly generated code during optimization)
answered 2008-09-16T14:04:48.790

Your Answer