简体   繁体   中英

Difference between a volatile and a pointer variable in c

volatile和指针变量都从地址获取值而不是优化,因此明显的不同。

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 (eg 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 eg 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM