Re: Volatile variable....
When we use the word Optimise, we mean that the variable in the memory can be changed only by the compiler whenever the code is executed. Volatile modifiers cannot be optimised by the compiler, During linking process the code is allocated physical memory in the internal memory. so during the link process( generation of .lnk file during compilation) these variables are placed in the heap instead of main memory. Compiler cannot modify the variable until unless a copy is copied to RAM for execution. So the compiler allocates a different memory location for the variable. These are called un-optimised location. the variables in this location are not dependent on the compiler to change the value. instead interrupt, ports, serial, hardware are given permission to access these variables when ever they raise a request.
When a memory is optimised, then the life of that variable is limited only till the function executes then it is destroyed, but volatile are not destroyed, but keep value in it till there is any change done by external entities. Whenever these variables are accessed only the last updated value is seen in the register.
Uploading a example after this. the best example is RTC(Real Time Clock). in the PC. even when the PC is shut down , and later restarted, the clock updates the latest current time.
Added after 9 minutes:
eg:
volatile char time;
void update(void)
{
time =time+1;
}
void main()
{
time=0;
while(time<100);
}
without volatile modifier the compiler looks at this as 2 different statements.
1. time =0;
2. while(time<100);
since time =0; 0<100, so the loop always stay in the same line till the condition is true.
Time never reach 100. So when memory is optimised then it can be changed only through execution of explicit statement which modify the value. in the above case it does not change.
if we use volatile modifier, this disables optimisation, forcing the program to fetch a new value from the variable every time variable is accessed.
hope this answers your question. if not then i can still continue my explaination in my next post. let me know if you got anything from this.
Always remember you cannot simulate the condition of volatile in c51 or any compiler as Heap memory cannot be simulated in keil. it can be seen only on hardware.
thanks
shivaram