“volatile” qualifier in C

C++Server Side ProgrammingProgramming

Here we will see what is the meaning of volatile qualifier in C++. The volatile qualifier is applied to a variable when we declare it. It is used to tell the compiler, that the value may change at any time. These are some properties of volatile.

  • The volatile keyword cannot remove the memory assignment
  • It cannot cache the variables in register.
  • The value cannot change in order of assignment.

Let us see, how we can use the volatile keyword.

volatile int a;
int volatile a;

Here these two declarations are correct. Like other datatypes, we can use volatile pointers, structures, unions etc. The volatile structures and unions can be volatile itself, and their member variables can also be of type volatile.

The volatile is used in different places. For memory mapped peripheral registers, some global variables, that are accessed by some other functions or interrupt service routines, or in some multi-threaded applications, the volatile can be used.

Example

int main (){
   int value;
   value++;
}i
nt main (){
   volatile int value;
   value++;
}

There are two blocks of code. In the first block the volatile keyword is not present. So for the first case, the variable will be copied from memory to CPU register, then the operations are performed. In the second case the volatile is present. So in this case the variable will not be copied from memory to registers.

raja
Published on 30-Apr-2019 16:13:01
Advertisements