Analysis pointers and pointers to constant const

  Analysis following definitions pointer p.

int tmp = 5;

int *p = &tmp;
const int *p = &tmp;
int const* p = &tmp;
int * const p = &tmp;
const int * const p = &tmp;
int const * const p = &tmp;

  According to a document, read from right to left distinguish embodiment may be employed.

The first is a normal pointer ordinary int variable;

The second and third identical, are common pointer const int type variables;

Const is a fourth pointer ordinary int variable;

The same as the fifth and sixth, are const pointer const int type variables.

 

  Experiment code is as follows:

 1 #include <iostream>
 2 
 3 
 4 void test1() {
 5     int tmp = 5;
 6     int *p = &tmp;
 7     std::cout << "test1:: p value: " << *p << std::endl;
 8     // *p and p are common variables.
 9     *p = 10;  // ok
10     int tmp1 = 9;
11     p = &tmp1;  // ok
12 }
13 
14 void test2() {
15     int tmp = 5;
16     const int *p = &tmp;
17     std::cout << "test2:: p value: " << *p << std::endl;
18     // *p is read-only, p is common variable.
19 //    *p = 10;  // error
20     int tmp1 = 9;
21     p = &tmp1;  // ok
22 }
23 
24 // same with test2
25 void test3() {
26     int tmp = 5;
27     int const* p = &tmp;
28     std::cout << "test3:: p value: " << *p << std::endl;
29     // *p is read-only, p is common variable.
30 //    *p = 10;  // error
31     int tmp1 = 9;
32     p = &tmp1;  // ok
33 }
34 
35 void test4() {
36     int tmp = 5;
37     int * const p = &tmp;
38     std::cout << "test4:: p value: " << *p << std::endl;
39     // p is read-only, *p is common variable.
40     *p = 10;  // ok
41 //    int tmp1 = 9;
42 //    p = &tmp1;  // error
43 }
44 
45 void test5() {
46     const int tmp = 5;
47     const int * const p = &tmp;
48     std::cout << "test5:: p value: " << *p << std::endl;
49     // p is read-only, *p is also read-only.
50 //    *p = 10;  // error
51 //    int tmp1 = 9;
52 //    p = &tmp1;  // error
53 }
54 
55 
56 // same with test5
57 void test6() {
58     const int tmp = 5;
59     int const * const p = &tmp;
60     std::cout << "test6:: p value: " << *p << std::endl;
61     // p is read-only, *p is also read-only.
62 //    *p = 10;  // error
63 //    int tmp1 = 9;
64 //    p = &tmp1;  // error
65 }
66 
67 int main() {
68     std::cout << "Hello, World!" << std::endl;
69     test1();
70     test2();
71     test3();
72     test4();
73     test5();
74     test6();
75     return 0;
76 }

 

References:

(1) https://www.cnblogs.com/bencai/p/8888760.html

Guess you like

Origin www.cnblogs.com/tlz888/p/11350521.html