and c the language of the pointer const

image.png

const and pointers

Difference method:

如果const位于*的左侧,则const就是用来修饰指针所指向的变量,即指针指向为常量; 

如果const位于*的右侧,const就是修饰指针本身,即指针本身是常量。

Const pointer

const close to the data type, the type of modification is the variable constant.

Example:

const int x = 20; // int type defined symbolic constant x, x = 20

const int * p = & x; // define a pointer pointing to a constant p,
// pointer can be changed, but can not be changed by a pointer in the value of x

Pointer constant

const near pointer, this pointer is defined as the constant pointer

Example:

int * const p2 = & x; // define constant pointer p2,
// pointer to immutable (constant pointer), but can be changed by the value of the pointer x

The wording of the relevant six

const int p;
 const int *p;
 int const* p;
 int * const p;
 const int * const p;
 int const * const p;

Authentication Code

#include <iostream>
using namespace std;
 
int main ()
{
    int x=10;
    int y=50;
    // the left modified variable immutable
    // pointer to constant 
    const int *p=&x;
    cout<<"p="<<p<<" *p="<<*p<<endl;
// * p = 20; // change the variable pointer, error: error C2166: l-value specifies const object
    p = & y; // pointer value which can change.
    cout<<"p="<<p<<" *p="<<*p<<endl;
    // constant pointer
    int * const p2 = & x; // const pointer near pointer p2 p2 inside the modified address value is not changed,
    cout<<"p2="<<p2<<" *p2="<<*p2<<endl;
// p2 = & y; // can not be modified, often pointers error C2166: l-value specifies const object
    * P2 = 30; // may modify the values ​​of the constant pointer variable
    cout<<"p2="<<p2<<" *p2="<<*p2<<endl;
    
    // define a pointer pointing to normally constant
    const int * const p3=&x;
    p3 = & y; // not change often pointing the pointer.
    * P3 = 100; // unchangeable constant value pointer constant.
//to sum up:
// const close to the data type is the type of repair to variable becomes constant,
// const pointer is modified to close the pointer becomes a constant pointer
    return 0;
}

If you have wanted to learn c ++ programmers, you can come to our C / C ++ learning buckle qun: 589348389,
free delivery C ++ Video Tutorial Oh!
Each 20:00 I will live in the group to explain the C / C ++ knowledge, welcome everyone to learn Oh.
 

Guess you like

Origin blog.csdn.net/XZQ121963/article/details/90778393