0

There are example console programs for volatile keyword in C++, in which removing volatile changes the output of the program. For example if the iterators of some for loops are volatile, the execution time is noticeably much longer; and this clearly proves that volatile has prevented an optimization.

In C#, I could not find an example of volatile in which an optimization is noticeably canceled. Do you have such an example working in Visual Studio compiler?

I mean an example in which removing the volatile keyword changes something in the output of the program.

Minimus Heximus
  • 2,683
  • 3
  • 25
  • 50
  • Have you tried searching the internet for `volatile C#`? There are explanations, examples and SO questions. Pay particular attention go what @ericlippert has said. Example: https://blogs.msdn.microsoft.com/ericlippert/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three/ – Flydog57 Jan 01 '20 at 14:50
  • @Flydog57 remoing `volatile` in the examples I found does not change anything noticeable. – Minimus Heximus Jan 01 '20 at 14:53
  • 1
    [Brian's snippet](https://stackoverflow.com/questions/6164466/a-reproducible-example-of-volatile-usage/6164770#6164770) is a notorious example with highly visible side-effects. He did forget to mention that you have to run it in 32-bit mode, only the x86 jitter optimizer has this behavior. Noteworthy perhaps is that the C++20 standard [has deprecated](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1152r3.html) most usage of volatile, this isn't just a problem in C#. – Hans Passant Jan 01 '20 at 15:08
  • 1
    You can look at [When to use the volatile keyword in C#](https://www.infoworld.com/article/3229360/how-to-use-the-volatile-keyword-in-c.html) to know how to use volatile keyword effect. – Jack J Jun Jan 02 '20 at 05:23

0 Answers0