Use of volatile for registers

寵の児 提交于 2019-12-24 09:34:10

问题


I am wondering how efficient / is working the volatile declaration. In the following code:

volatile char var1 = * (volatile char *) 0x2000000;
printf("%d \n", var1 + 1);

It means that every time I am using the variable "var", it will be loaded from the address memory 0x2000000, but is the volatile cast of a fixed address necessary, or is it only to fit the type of var1?

Does this means that every time "var1" is read, it is read from memory, and not from a potential cached value? So in this code, we access two times the address 0x2000000?


回答1:


but is the volatile cast of a fixed address necessary, (?)

Yes, consider the below. Compiler could reason (char *) 0x2000000 was read once, no need to read again for volatile char var2 = * (char *) 0x2000000;. Just use the value that was read before and saved away in some internal memory/register. Targets var1/var2, being volatile, do not affect the right-hand-side of the assignment.

volatile char var1 = * (char *) 0x2000000;
printf("%d \n", var1);
volatile char var2 = * (char *) 0x2000000;
printf("%d \n", var2);

The volatile with volatile char var1 is not needed. Defining a pointer to volatile data is likely more in line with coding goals.

volatile char *ptr1 = (volatile char *) 0x2000000;
printf("%d \n", *ptr1);
printf("%d \n", *ptr1);  // A 2nd read of `(volatile char *) 0x2000000` occurs.



回答2:


As you have written it, volatile char var1 = * (volatile char *) 0x2000000;, this says to create an object named var1 (allocated at a place the C implementation chooses) and to initialize it to a value read from 0x2000000. Every time var1 is read, the copied value will be read from the place the implementation allocated. It will not be reread from 0x2000000.

You may want volatile char *var1 = (volatile char *) 0x2000000;. This defines var1 to be a pointer to 0x2000000. With this definition, every time *var1 is used, the value will be read from 0x2000000.



来源:https://stackoverflow.com/questions/49039977/use-of-volatile-for-registers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!