Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Constants  and  Pointers

When   dealing   with   pointers,   the  situation   is   a   little   confusing  because  now two  objects  involved : the  pointer  itself  and  the  object  to  which  the  pointer  points. It  is  a  compile-time  error  to  assign  the  address  of  a  constant  to  a  pointer. Otherwise,  the  constant  value  could  be  changed  indirectly  through  the  pointer.


For  example,   const  int  A = 12;
int *  ptr = &A ;   // error


However  we  can  declare  a  pointer  that  addresses  a  constant.


For example,   const  int *  ptr;  // need  not  initialize,  pointer  to  a  constant


It  can  point  to  any  variable  of  correct  type,  but  the  contents  of  what  it  points to cannot  be  changed.


ptr  is  a  pointer  to  a  const  object  of  type  int.
*ptr  is  a  const  and  ptr  is  not  a  const.


The  address  of  a  const  variable  can  be  assigned  to  a  pointer  to  a  const, such as


const  int *  ptr ;
const int  A = 14 ;
ptr = &A ;  // ok  A  is  a  const
*ptr = 83 ;  // error  cannot  modify  a  const  object


The  programmer  may  also  define  a  const  pointer.


For   example,  int  i ;
int *  const ptr = &i ;  // constant  pointer


Here  ptr  is  a  constant  pointer  to  an  object  of  type  int.  The  programmer  can modify  the  value  of  the  object  ptr  addresses.


For  example,   *ptr = 99 ;  // ok


but  cannot  modify  the  address  that  ptr  contains.


For  example,  int  a = 123 ;
ptr = &a ;  // error -- cannot  modify  the  address  that  ptr  is  initialized  to.


We  can  also  declare  both  the  pointer  and  the  variable  as  constants  in  the following  way:


const  int  v = 12 ;
const  int *  const ptr = &v ;  // ok


In  this  case,  neither  the  value  of  the  object  nor  the  address  itself  can  be changed.