Q: Give an example for the use of volatile keyword in c++ ?
- Show Answer
- Workspace
- Discuss
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.
Similar Questions
Since Nithya and Suganya exchange places, so Rita’s new position is the same as Monika’s earlier position. This position is 17th from the right and 10th from the left. Therefore Number of girls in the row = (16 + 1 + 9) = 26.