Search code examples
cvolatile

Proper use of volatile keyword in C


I am a beginner with C and i came across to the following code:

#include "stdio.h"

unsigned int ReturnSquare(void);

int main(void) {

int k;
int *mPtr;

mPtr = (int*) 0x1234;

*mPtr = 10;

 k = (int) ReturnSquare();

 printf("%p --> %d\n",mPtr,k);

}

unsigned int ReturnSquare(void)
{
  unsigned  volatile int a = * (unsigned volatile int *) 0x1234;
  unsigned  volatile int b = * (unsigned volatile int *) 0x1234;
  return a * b;
}

Could you please help me understand what is the use of volatile in this code?

It seems that the program does not work correctly. Any suggestion and explanation is very welcome. Thank you in advance.


Solution

  • When you read the same register twice the compiler can decide to optimize the behaviour.

    It could turn the code into something like this:

    unsigned  int a = * (unsigned int *) 0x1234;
    unsigned  int b = a;
    

    When you add volatile the compiler will make no assumption on the second read that the value will be the same and it will generate the extra instructions for dereferencing the pointer to register again.

    It might be too advanced for you right now but you can check this with the assembly output option on your compiler, the volatile version will have more assembly instructions.