Jun 16, 2016

C Programming #69: Volatile pointers

C Programming #69: Volatile pointers

This article discusses volatile pointers construct in C Programming. You can review C Programming #68: Volatile variable before continuing. As we can make variables as volatile to prevent unwanted compiler optimization. In similar way we could also have pointers as volatile. There are there types of volatile pointers.


Consider following example for discussion

int a;
int *p = &a;

In the above example, p is pointer and a is pointee to which pointer points to.

Volatile pointee

When we know the a could change unexpectedly (then a would be make volatile) and pointer to a would be defined as follows.

volatile int a;
volatile int *p = &a;

Here compiler would not optimize any de-reference of p. Since the pointee is volatile. Any access of p could be still optimized.

Volatile pointer

When we know that pointer value only could change unexpectedly then following declaration is used.

int a;
int* volatile p = &a;

Here compiler would not optimize any access to p it self. De-reference could be still optimized.

Volatile pointer and pointee

Now this the combination of both of the above.

volatile int a;
volatile int* volatile p = &a;

Here both pointer access and deference would not be optimized. The above concept applies to all the pointer variables.

No comments :

Post a Comment