1. Pointer variables pointing to constants
A pointer variable that points to a constant is defined by:
Const type identifier * pointer variable name;
Such as:
const int *p;
The pointer variable defined by this method can read only the value of the variable or constant it points to, and it cannot be modified (that is, re-assigned) by the pointer variable to the value of the object it points to. However, this pointer variable can be allowed to point to another variable of the same type.
I self-study, the textbook may be a bit old, there are problems to ask you correct!!! Thank you!!!
2. Pointer constants
The definition format for pointer constants:
Type identifier *const pointer variable name = initial pointer value;
Such as:
Char * const p="abcde";
The method defines a pointer variable whose value (which is a pointer value) cannot be modified (that is, the pointer variable is not allowed to point to another variable), but the pointer variable can be used to read or modify the value of the object it points to. It is particularly important to note that this pointer must be initialized when defined.
3. Pointer constants pointing to constants
The first method for pointer constants pointing to constants is:
Const type identifier * Const pointer variable name = initial pointer value;
Such as:
int b;
const int* const p=&b;
A variable defined by this method does not allow modification of the value of the pointer variable or the value of the object to which it points by using the pointer variable. It is important to note that the variable must also be initialized at the time of definition.
Examples:
- Pointer variable pointing to constant
1#include <iostream>2 using namespacestd;3 4 intMain ()5 {6 Const intI= -;7 intK = +;8 Const int*p;9p=&i; Tencout << *p <<' '<< I <<Endl; Onep=&K; Acout << *p <<' '<< k <<Endl; -k= $; -cout << k <<Endl; the return 0; -}
1#include <iostream>2 using namespacestd;3 4 intMain ()5 {6 Chars[]="Hello world!";7 Char*Constp=s;8 //p= "XYZ"; //This is an error, and you can no longer point the pointer variable to another address (pointer)9cout << *p <<Endl;Ten*p='W'; Onecout << *p <<Endl; A*p='Q'; -cout << *p <<Endl; - return 0; the}
- Pointer constants pointing to constants
1#include <iostream>2 using namespacestd;3 4 intMain ()5 {6 intA=Ten;7 intC= -;8 Const intb= -;9 Const int*Constp=&A;Tencout << *p <<Endl; One Const int*Constq=&b; Acout << *q <<Endl; - //p=&c;//Error - //*p=50; //Error the return 0; - } - - //Rookie, please criticize advice, code writing habits and norms and so on!!! Thank you!!!
I self-study, the textbook may be a bit old, there are problems to ask you correct!!! Thank you!!!
C++const and pointers