Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.
Volatile means that a variable can be altered from an external source (like interrupt) and the optimizer of the compiler can not assume that the variable stays unchanged between accesses.
With microcontrollers for example the ports are declared as volatile in the header file of a processor.
This is from the Hi-Tech C manual:
The volatile type qualifier is used to tell the compiler that an object cannot be guaranteed to retain its
value between successive accesses. This prevents the optimizer from eliminating apparently redundant
references to objects declared volatile because it may alter the behaviour of the program to do so. All
Input/Output ports and any variables which may be modified by interrupt routines should be declared
volatile, for example:
volatile unsigned char P_A @ 0x05;
At first glance you are tempted to declare all variables in your program volatile (because you can use them safelly in interupts, for example)
Every time you declare a variable volatile, the compiler reserve a location of memory only for that variable , this location cannot be used anymore by the overlay processor (wich can free memory resources when not nedeed).
On an embedeed processor with low RAM memory, the generated code will poorly optimized (read: low execution time)
#1 Compilers try to optimize your code as much as they can. In douing so they may chose to ignore certain statements you wrote simply because in their opinion they may be redundant. For example:
Code:
{
int i;
i = 10;
i = 20;
printf("\n%d", i);
}
clearly, the first assignment is redundant and the compiler will choose to ignore it when it optimizes the code.
#2 There may be situations in which such kind of optimizations are undesirable. For example the situation listed by C-Man. In general if you have a variable that may be modified from some other thread, then in such cases, optimizations should not be allowed. Now the question is how to instruct the compiler that optimization is not to be performed for this particular variable? Yes you guessed it! declare it volatile.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.