View Single Post
  #10   Spotlight this post!  
Unread 08-02-2004, 15:34
Dave Flowerday Dave Flowerday is offline
Software Engineer
VRC #0111 (Wildstang)
Team Role: Engineer
 
Join Date: Feb 2002
Rookie Year: 1995
Location: North Barrington, IL
Posts: 1,366
Dave Flowerday has a reputation beyond reputeDave Flowerday has a reputation beyond reputeDave Flowerday has a reputation beyond reputeDave Flowerday has a reputation beyond reputeDave Flowerday has a reputation beyond reputeDave Flowerday has a reputation beyond reputeDave Flowerday has a reputation beyond reputeDave Flowerday has a reputation beyond reputeDave Flowerday has a reputation beyond reputeDave Flowerday has a reputation beyond reputeDave Flowerday has a reputation beyond repute
Re: volatile keyword

Quote:
Originally Posted by mightywombat
What does the volatile declaration mean?
Volatile is a hint to the compiler to tell it that the memory location where the variable which was declared "volatile" is stored can change without the compiler knowing about it. This is significant, because a common optimization that a compiler will make with variables is that it will try to minimize the number of times a variable is copied out of RAM and into a register inside the CPU. Meaning if you use a variable named "blah" several times in a function and it's stored in the memory address 1234, the compiler will copy the value from memory location 1234 to a register at the beginning of the function, then use the register each time your code accesses that variable, and then just save the contents of the register back to memory address 1234 at the end of the function.

When you tell the compiler that a variable is "volatile" it means that it can be changed by something other than the code which the compiler is generating. So, when the compiler sees this, it does not cache the variable in a register and instead reads it directly out of RAM each time it is needed. Where this becomes important is on the digital I/O for example. The digital inputs are memory mapped (meaning to read the digital inputs, you just read a memory location). If these are not declared volatile, each time you access the digital inputs you may not be receiving the newest available data. So, if you go and look at ifi_picdefs.h, you'll see that all the CPU registers are declared volatile for this reason.

Hope that made sense, it's pretty tricky to explain in text without a whiteboard . Let me know if you want me to clarify any part of it...