volatile variables ? example
In embedded we deal with special features in c language that are provided to make building systems convenient. One such feature is volatile variable :
A variable should be declared volatile whenever its value could change unexpectedly viz by external influences like the variable representing memory mapped peripheral register.
Example:
static int var;
void test(void)
{
var = 0;
while (var != 255)
continue;
}
The above code sets the value in var to 0. It then starts to poll that value in a loop until the value of var becomes 255.
An optimizing compiler will notice that no other code can possibly change the value stored in 'var', and therefore assume that it will remain equal to 0 at all times. The compiler will then replace the function body with an infinite loop, similar to this:
void test_opt(void)
{
var = 0;
while (TRUE)
continue;
}
solution is :
volatile int var;
A variable should be declared volatile whenever its value could change unexpectedly viz by external influences like the variable representing memory mapped peripheral register.
Example:
static int var;
void test(void)
{
var = 0;
while (var != 255)
continue;
}
The above code sets the value in var to 0. It then starts to poll that value in a loop until the value of var becomes 255.
An optimizing compiler will notice that no other code can possibly change the value stored in 'var', and therefore assume that it will remain equal to 0 at all times. The compiler will then replace the function body with an infinite loop, similar to this:
void test_opt(void)
{
var = 0;
while (TRUE)
continue;
}
solution is :
volatile int var;
Comments
Post a Comment