1

Do we need to use volatile qualiifier when all kind of compiler optimization has been turned off, assuming it was required when we had compiler optimization enabled.

I read the post on SO Volatile and compiler optimization which says yes, but doesn't give any specific use-case where it is required.

Can someone point out the cases where their use is still required irrespective of any kind of optimization being enabled or disabled.

Dinesh Maurya
  • 822
  • 8
  • 24
  • 3
    The C++ standard does not sepcify "compiler optimization". –  Jun 01 '17 at 13:02
  • 3
    So C or C++? C and C++ are different languages and you should only tag with one, if you want a good answer. Preferably it would be a good idea to also tag the C/C++ version you want the answer for. That said, as @manni66 mentioned, the standard doesn't specify such behaviour. – tambre Jun 01 '17 at 13:03
  • One such use case is when you're using a pointer to a memory mapped address. – Jesper Bangsholt Jun 01 '17 at 13:03
  • 3
    `volatile` specifies how the program must access the value represented, it is tangential to optimization – kmdreko Jun 01 '17 at 13:06
  • [This SO article](https://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c) may be interesting – Jabberwocky Jun 01 '17 at 13:14
  • I smell the common misconception that there is some kind of pure, unoptimized code that the compilers will generate where one line of code corresponds exactly to one block of instructions. There is no such thing. If a compiler is written in such a way that reordering, using registers, inlining and such is as efficient as not doing it, it will do it anyway. Optimization is just another way to say "spend some extra time and effort to make generated code better". – Art Jun 01 '17 at 14:20

1 Answers1

7

If you need volatile for your program to be correct with optimization, then you also need it without optimization. Optimization only changes incorrect programs between various states of incorrectness.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Only changes the *behaviour* of incorrect programs between different incorrect *behaviours* – Caleth Jun 01 '17 at 13:23