Search code examples
cvolatile

Use of volatile for registers


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?


Solution

  • 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.