What is the use of volatile keyword in C?
i. it is to tell the compiler to not optimize the code that access that variable.
ii. it is to tell the compiler that don't remove that variable from the memory to registers while optimizing.
iii. it is to tell the compiler that, the volatile variable may be accessed by outside environment, so don't optimize it or don't change its location.
i & ii
i, ii, & iii
There are lot of uses case with volatile keyword in C. generally c compiler will do lot of optimization to our code to run fast on our device. while doing like that, it may move some of the variables from memory to cpu registers because accessing registers will be faster than accessing memory. similarly if compiler sees if some of the variables are not used by our code, then it may remove that variable from the code, but that variable might be used by some outside environment code. To avoid such kind of mistakes we make that variable as volatile if we don't want compiler to optimize the code which access that variable.
Back To Top