Difference between a volatile and a pointer variable in c
Both volatile and pointer variable fetch the value from the address rather tha开发者_JAVA技巧n optimizing, so what is clear difference.
volatile
is a storage class, along with register
, static
, external
. volatile
says that the value of a volatile variable could be changed by other forces besides the running program, so the compiler must be careful to not optimize fetching a fresh copy of the variable with each use.
A pointer contains the address of a memory location. To access what it points at, it must be dereferenced.
Volatile is an indication to the compiler to re-fetch the value from the memory location than use the value stored in registers. This is because the memory location may have been updated (e.g. by other threads). That is the meaning of
fetch the value from the address
not act as a pointer. You can also volatile a non-pointer variable e.g. primitive.
So an int variable is refetched and not use the stored value in registers.
It also enforces certain semantics concerning read/write (but this is not related to your OP)
Volatile
is a storage class which tells the compiler to fetch the value from memory every time it is accessed and write to it every time it is written. It is usually used when some entity other than your program may also change the value at a certain address.
Compilers optimize the programs in many ways. For example if you have following code:
int *ptr=0x12345678;
int a;
*ptr=0x10;
a=*ptr;
then the compiler may optimize the statement a=*ptr;
to a=0x10;
to avoid memory access. the justification is that because you just wrote 0x10; to *ptr so when you read *ptr you are going to get 0x10.
In normal cases this assumption is true but consider the case where the address 0x12345678 is the address of some memory mapped register of an embedded system's UART and writing 0x10 to it tells it to read a character from console attached. The character that is read is then written back to address 0x12345678 so the user can get it from there. Now in this case the above optimization will cause problems. So you want something to tell the compiler to to read/write the value to pointer every time it is accessed and don't optimize accesses to it. So you declare the pointer ptr volatile telling the compiler not to optimize accesses to it.
volatile int *ptr=0x12345678;
Volatile: A type specifier that tells the compiler to access the variable from its memory location (do not put in the register for fast access even if the program does not change the value) because the value of a volatile variable can be changed from outside the program (example IO Ports in a microcontroller) or from the ISR.
Pointer: The pointer variable is used to hold the address of a variable.
Volatile Pointer: Tells the compiler to read the value pointed by a pointer from its location only (for example GPIO pointers in a microcontroller).
精彩评论