Thursday, September 16, 2010

Pointers to Volatile

You cannot assign a 'pointer to volatile' to a 'pointer to non-volatile', but you can assign a 'pointer to non-volatile' to a 'pointer to volatile'.

This is similar to the rules for 'pointer to const' and 'pointer to non-const'.

You cannot assign a 'pointer to const' to a 'pointer to non-const', but you can assign a 'pointer to non-const' to a 'pointer to const'.

It is like 'pointer to volatile' and 'pointer to const' have special powers during assignment.

To force the assignment for either one, you would need to use const_cast<>() to cast away the volatile or const.

Here is a code example:

#include 
#include 
using namespace std;

int main() {
   volatile int    i_volatile = 3;
            int    i          = 5;
   const    int    i_const    = 7;
   volatile int * pi_volatile = &i_volatile;
            int * pi          = &i;
   const    int * pi_const    = &i_const;

   i = i_volatile;
   i_volatile = i;

   ///////////////////////////////////////////
   // The following line does not compile:
   //   pi     = pi_volatile;
   ///////////////////////////////////////////
   pi_volatile = pi;

   ///////////////////////////////////////////
   // The following line does not compile:
   //   pi  = pi_const;
   ///////////////////////////////////////////
   pi_const = pi;

   return 0;
}

No comments:

Post a Comment