0

I was reading about the volatile keyword in c++ and tried this sample piece of code which gave the result as follows:

sample code block

When I added the volatile keyword to the const var declaration the output became 200 for both vars. Can someone explain what kind of var optimizations the compiler might've done here? Thanks!

Community
  • 1
  • 1
supra
  • 49
  • 6
  • 3
    Modifying a const object results in _undefined behavior_. – Daniel Langr May 23 '20 at 11:26
  • 1
    Also, don't paste images of code. Always paste the code as text instead, such as others may copy it. – Daniel Langr May 23 '20 at 11:31
  • I expected the same. But when I added volatile it was working very well. I couldn't understand how it worked in the background. – supra May 23 '20 at 11:31
  • Study the generated assembly if you want to explain undefined behavior. – Daniel Langr May 23 '20 at 11:31
  • Yes, thank you. I somehow managed to miss this in all the open tabs I have. – supra May 23 '20 at 11:35
  • BTW, note that `volatile` very very rarely make sense together with `const`. The latter basically says that the object **is immutable** while the former that it **may be mutated** at any time from outside by some external mechanism, which is in contradiction. – Daniel Langr May 23 '20 at 11:36
  • @DanielLangr: read-only and immutability are different though (The later implies the former). and volatile read-only might make sense. – Jarod42 May 23 '20 at 12:29

0 Answers0