const and Pointers

There are 4 possible combinations of using const with a pointer:

double *ptr1 ; const double *ptr2 ; double * const ptr3 ; const double * const ptr4 ;

How are these definitions different?




const and Pointers

double *ptr1 ; const double *ptr2 ; // points to const double * const ptr3 ; const double * const ptr4 ; const double PI = 3.14159268 ; ptr1 = &PI ; // not OK ptr2 = &PI ; // is OK ptr3 = &PI ; // not OK ptr4 = &PI ; // not OK *ptr2 = 1.414 ; // not OK ptr2++ ; // bad idea, but allowed



const and Pointers

const double PI = 3.14159268 ; double * const ptr3 = &PI ; // not OK const double * const ptr4 = &PI ; // OK double x = 1.414 ; double * const ptr3a = &x ; //OK *ptr3a = 2.0 ; // allowed ptr3a++ ; // not allowed