C++ Const Double Pointer – Explanation and Usage

c++const-pointerconstants

I want to make a constant double pointer points to a constant pointer points to a constant double. I started to make it (of course I make a little search at books and I googled it) from scratch and think what the following three make:

const double* cp; //pointer to a constant double
double *const cp; //constant pointer
const double *const cp; //constant pointer to a constant double

I thought the next step is to write a constant double pointer

double **const cp;// double constant pointer

then I combine the last two statements and I write

const double *const cp = arr[0];
double **const cp1 = arr ;

where arr is a dynamically allocated double dimension array.
After that I tried to verify what I have done and I wrote the below statements expecting to produce error all of them.

**cp1 = 1;    // didn't produce error  
*cp1 = arr[4];    // didn't produce error
cp1 = new double*[5]; //produce error   

So the thing is that I couldn't make what I described above , a constant double pointer points to a constant pointer points to a constant double. How can I make it ?

Thanks in advance.

Best Answer

There's only one const in

double **const cp1 = arr ;
//       ^^^^^

so I'm not sure why you're expecting the other two assignments to produce an error.

If you want it to be const on all levels, you need

const double *const *const cp1 = arr;
//                         ^ cp1 is ...
//                  ^ a const pointer to ...
//           ^ a const pointer to ...
// ^ a const double
Related Question