The const qualifier in c++ primer

  • 2020-09-16 07:41:34
  • OfStack

const qualifiers

The & # 8194; const is a type modifier that describes objects that never change. Once the const object 1 is defined, no new values can be assigned, so it must be initialized.

Ex. : const int bufsize = 512;

Its value of 1 cannot be changed once it is defined and, by default, is only valid within the file.

If you want to share const objects in multiple files, you need to add extern before defining and declaring them.

Initialize and reference to const

Ex. :


const int ci = 1024;
const int &r1= ci;
r1 = 42; //  Values cannot be changed 
int &r2 = ci; // Error, non-constant references cannot point to constant objects. 
int i=42;
const int &r1 = i;
const int &r2 = 42;
const int &r3 = r1 * 2;
//  All the above expressions are correct and allowed 1 A constant reference binds an object, a literal, or even a 1 General expression. 
int &r4 = r1*2; //  Error; r4 not 1 Cannot be initialized with a constant reference. 

The following exceptions:


double dval =3.14;
const int &r = dval;

The above expression is correct, while the direct following is incorrect;


double dval= 3.41;
int &r = dval; // double A reference to a type cannot be int Type. 
//  Reason: The purpose of a reference is to change it by reference dval The value of, otherwise to give r What's the assignment? So c++ The rules are against the law. 

The reason is that when a constant reference is assigned, the value of the subsequent constant reference cannot be changed, so there is no point in changing the value of dval by reference. At compile time, the above code will look like this:


const int temp = dval;
const int &r = temp;

const Pointers:


int errNumb = 0;
int *const curErr = &errNumb; // curErr will 1 Aimed at errNumb //  The pointer itself is 1 A constant does not mean that the value of the object to which it refers cannot be modified by a pointer // This place refers to curErr The address you store cannot be changed.  
const double pi = 3.14159;
const double *const pip = &pip; //pip is 1 A constant pointer to a constant object 

The top const

The top const indicates that the pointer itself is a constant;

The object to which the underlying const pointer refers is 1 constant.


int i = 0;
int *const p1 = &i; // Can't change p Theta. This is theta 1 A top const
const int ci = 42 ;  // Can't change ci Theta. This is theta 1 A top const
const int *p2 = &ci; // Allowed to change p2 Theta. This is theta 1 A bottom layer of const
const int *const p3 = p2; // On the right const Is at the top of the const , on the left const Is at the bottom of the const
const int &r = ci ;  //  Used to declare references const It's all bottom level const . 

conclusion


Related articles: