Understanding Volatile in C


We can actually force compiler to do what we write by, declaring the pointer gadget as volatile. It can’t cache variables in registers, can’t remove the memory assignments and even can’t change the order of assignments.

The corrected code for above is as follow:

void SendCommand (volatile MyGadget * gadget, int command, int data)
{
  // wait while the gadget is busy:
  while (gadget->isbusy)
  {
    // do nothing here.
  }
  // set data first:
  gadget->data    = data;
  // writing the command starts the action:
  gadget->command = command;
}

Register example

Embedded system consist real hardware with sophisticated peripherals, which contains registers whose values may change any time irrespective to program flow. Take an example where we consider a eight-bit register, memory mapped at an address 0x5555. It is
required that you poll the register until it becomes non-zero.
Let us put it as follow:

Uint8_t *sReg = (uint8_t *)0x5555;

// Wait for register to become non-zero 

while (*sReg == 0) { } // Do something else

As you turn compiler optimization on, it shows error. To force the compiler to do what we want, we modify
the declaration to:


 

uint8_t volatile * sReg = (uint8_t volatile *) 0x5555;

The point of all this is that volatile can be extremely useful in many circumstance but you must use it judiciously.
It is not meant to be a cure-all and certainly should not be used under the assumption that it will somehow standardize
the way the underlying system(s) operates. The only effect of using volatile is during code compilation.
If you remember those simple facts you will be fine.

Related posts:

About author

This article was written by admin

Admin has over twenty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles. Working presently as Development Manager in India. A firm Believer in Knowledge grows when it shared.

Comments

Comments (1)

Leave your comment

Your email address will not be published. Required fields are marked *