What is the use of volatile keyword in c++ ? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 6

What is the use of volatile keyword in c++ ?

I need answer

26th Jul 2017, 6:53 AM
Shweta Kumari
Shweta Kumari - avatar
5 Respostas
+ 11
A rather lengthy and good reply which I am also going to digest later. :> https://stackoverflow.com/questions/4437527/why-do-we-use-volatile-keyword-in-c
26th Jul 2017, 6:58 AM
Hatsy Rei
Hatsy Rei - avatar
+ 9
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a volatile object from the memory location rather than keeping its value in temporary register at the point it is requested, even if a previous instruction asked for a value from the same object.
26th Jul 2017, 3:19 PM
Shweta Kumari
Shweta Kumari - avatar
+ 2
volatile keyword avoids the compiler for implicit conversion or to optimize the loops or iteration statements.
26th Jul 2017, 7:06 AM
Lakshay
Lakshay - avatar
+ 1
I have never seen anyone using it, but it is as they said, to stop compiler from changing your code during optimization.
26th Jul 2017, 7:51 AM
Denis Felipe
Denis Felipe - avatar
+ 1
The explanation of Shweta makes sense, since using the cache can lead to problems if the value in the register is being changed by other programs. It even gives meaning to the word volatile.
26th Jul 2017, 3:22 PM
Denis Felipe
Denis Felipe - avatar