A variable defined as volatile means that the variable may be unexpectedly altered so that the compiler does not assume the value of the variable. Precisely, the optimizer must carefully reread the value of the variable every time it uses it, instead of using a backup stored in the register. Here are a few examples of volatile variables:
1. Hardware registers for parallel devices (e.g., status registers)
2). Non-automatic variable (non-automatic variables) that is accessed in an interrupt service subroutine
3. Variables shared by several tasks in multi-threaded applications
A person who cannot answer this question will not be hired. I think this is the most basic problem to differentiate between C programmers and embedded system programmers. Embedded system programmers often deal with hardware, interrupts, RTOs, and so on, which require volatile variables. Not knowing volatile content will bring disaster.
Assuming the interviewer has answered the question correctly (well, doubt it will be), I'm going to delve a little deeper and see if this guy is straight and understands volatile's full importance.
1. Can a parameter be either a const or a volatile? explain why.
2). Can a pointer be a volatile? explain why.
3). What's wrong with the following function:
int square (volatile int *ptr)
{
return *ptr * *PTR;
}
Here is the answer:
1). Yes. An example is a read-only status register. It is volatile because it can be changed unexpectedly. It is const because the program should not attempt to modify it.
2). Yes. Although this is not very common. An example is when a medium service subroutine fixes the pointer to a buffer.
3. There's a prank on this piece of code. The purpose of this code is to return the pointer *ptr to the square of the value, but since *ptr points to a volatile parameter, the compiler will produce code similar to the following:
int square (volatile int *ptr)
{
int a,b;
A = *ptr;
b = *ptr;
return a * b;
}
Because the value of the *ptr can be unexpectedly changed, A and B may be different. As a result, this code may not return the square value you expected! The correct code is as follows:
Long Square (volatile int *ptr)
{
int A;
A = *ptr;
Return a * A;
}