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

There  are  two  ways  of  creating  constants  in  C++


1.  Using  the  qualifier  const
2.  Defining  a  set  of  integer  constants  using  enum  keyword


Any  variable  declared  as  const cannot  be  modified  by  the  program  in  any way .  The   const  modifier  is  used  to  make  a  variable  value  unmodifiable.  Any  attempt  to change the  value  will  result  in  a  compile-time  error.


For  example,  const  int  size = 18 ;
size++ ;   //error: cannot  modify


C++  requires  a  const  to  be  initialized.


For  example,  const  int  number ;  // error  uninitialized  const



Another  method  of  naming  integer  constants  is  as  follows :


enum  { A, B, C } ;


This  defines  A, B, C  as  integer  constants  with  values  0, 1,  and  2  respectively.  This  is equivalent  to :


const  int  A = 0 ;
const  int  B = 1 ;
const  int  C = 2 ;


We  can  also  assign  values  to  A, B,  and  C  explicitly.


enum  { A = 10, B = 12, C = 20 } ;


Such  values  can  be  any  integer  values.