Join Examsbook
1023 0

Q: Give an example for the use of volatile keyword in c++ ?

  • Show AnswerHide Answer
  • Workspace

Answer :
Explanation :

Most of the times compilers will do optimization to the code to speed up the program. For example in the below code, int k = 15;while( k == 15) { // Do something} compiler may think that value of 'k' is not getting changed in the program and replace it with 'while(true)', which will result in an infinite loop. In actual scenario, the value of 'k' may be getting updated from outside of the program. Volatile keyword is used to tell compiler that the variable declared using 'volatile' may be used from outside the current scope, so that compiler won't apply any optimization. This matters only in case of multi-threaded applications. In the above example if variable 'k' was declared using volatile, compiler will not optimize it. In shot, value of the volatile variables will be read from the memory location directly.

Are you sure

  Report Error

Please Enter Message
Error Reported Successfully