How to distinguish between C/C ++ constant pointers and pointer constants

Source: Internet
Author: User
Tags constant extend

Constant pointers and pointer constants in C ++ are easy to confuse. Actually there is nothing. This is nothing more than the difference between the const int * p and the int * const p, but when it comes to the first name, in particular, because of the differences between the author and the translator (for external documents, there is a mess like "Zhang Guanli Dai" and "Li guanzhang Dai". I don't know who it is, and it makes people confused, especially for beginners. The purpose of this article is to give a clear explanation of the two and illustrate the differences in use.

Note: 1. const int * p can also be written as int const * p, that is, there is no difference between the const int and int const in C ++, which makes it even more troublesome to be confused, in this article, I only use the const int.

2. If you hate it ?? Close? What is zookeeper ?? Treasure disaster recovery benzene? Health saddle material cutting beer ?? What is the title of the coin called? Are you sure you want to get it ?? Playing ?? Br/>
Let's take a look at the current situation of chaos.

1. const encounters pointer

The opposite explanation of the same problem

1. Unconventional minority

The fifth edition of C ++ Primer is contrary to other C ++ books.

Constant pointer -- int * const p

Pointer to a constant -- const int * p

In the English version, int * const p is called const pointer, so the Chinese version translates it into a constant pointer, while const int * p is called pointer to const, however, the Chinese version does not translate it into a pointer constant, but a pointer to a constant.

Coincidentally, our domestic book "C ++" (Fan Lei, the 2010 version of Tsinghua University Press) is completely consistent with C ++ Primer, call int * const p a constant pointer, and call const int * p a pointer to a constant.

2. One-sided comments from the masses

What is more widely used?

Constant pointer -- const int * p

Pointer constant -- int * const p

I have read a book named "constant pointer" and "pointer constant"-"C ++ object-oriented programming" (Guo Youqiang published by Tsinghua University Press in 2009) (from the years of publication, we can boldly speculate that older books will be mentioned in this way ). In more books, we call int * const p a pointer constant and const int * p a pointer to a constant. (The key to the problem is int * const p. Some books call it a constant pointer, for example, 1. Some books call it a pointer constant, for example, 2)

Here, "one side down" is more important for the network. If your Baidu "constant pointer and pointer constant", you will see that almost all the materials use the 2 formula. If a beginner first chooses the network path to solve the confusions of "constant pointers and pointer constants", then the concept of "2" should be rooted in his mind.

If you have accepted the formulation in 2, we recommend that you extend "constant pointer" to "pointer to constant ", extend "pointer constant" to "this pointer is constant" to help you remember and differentiate the essence of both.

Saving the authors

Some IT educators and practitioners have also noticed this problem. In recent years, some book authors have begun to use their own methods to correct IT. Let's see how they did IT.

1. Will this change work?

Const int * p is called a constant pointer target expression in C ++ Programming Basics (published by Tsinghua University Press in 2013 ", int * const p is called a constant pointer variable. Can you remember the long name? Remember, can you figure it out?

2. You can't figure out either of them.

The famous foreign language book C ++ advanced programming (the second Chinese edition) under the title of "const pointer", the const int * p and int * const p are introduced without their specific names.

In China, "new standard C ++ Programming Tutorial" (Guo Wei published by Tsinghua University Press in 2012) calls const int * p a constant pointer, when we introduced int * const p, we wrote "There is also a constant pointer ".

However, this still cannot be called effective because it does not distinguish the two by name, and "different things, the same name" is not easy to communicate.

3. A recommended naming method

C ++ Programming Tutorial (published by Beijing University of Posts and Telecommunications Press in 2009) and C ++ from entry to mastery (published by People's Post and Telecommunications Publishing House in 2015)

Pointer variable pointing to a constant -- const int * p

Pointer constant pointing to a variable -- int * const p

Pointer constant pointing to a constant -- const int * const p // will be detailed later

In this way, who often becomes clear, and the name reflects the essence. From the year of publication of the first book, we can see that such a clear naming method has been available several years ago, but unfortunately, until now, among many C ++ books, this clear naming method is rare.

Intention

Some people will say, "You have said so much and have not brought us any substantive knowledge ." I don't have any objection. In fact, I 've already been awake at the beginning of this section. You can skip this section. The intention of writing this part below is as follows:

1. Introduce the current situation and common ideas to readers.

2. Tell the readers about inconsistency in this issue. When reading different books, do not be too confused.

3. Advise readers not to remember "constant pointers" and "pointer constants" on the Internet, because such names are not good and many books have not mentioned them at the same time.

4. Express your desire to name C ++ in terms of terminology, standardization, and unification, even though it is difficult to achieve this.

What can I do next?

1. Do not use "constant pointer" or "pointer constant", especially the latter, because it does not clearly express the meaning of "expressing an object as a pointer.

2. We recommend that you use the name under "a recommended naming method.

3. Or use the following suggestions. The description below

Pointer to a constant -- const int * p

Itself is a constant pointer -- int * const p

Const int * const p

Here, the structure of "attribute + subject" is used. The "pointer" of the subject represents the essence of the object to be described as a pointer, while the attribute describes the characteristics, at the same time, we can differentiate ourselves from others, which is easy to understand. (I always think that sometimes the name of a tall person is an easy-to-understand name, and it is a real tall person. It is intended for beginners and has always been the purpose and pursuit of the next article .) The only deficiency may be that the name is a little long, but I believe that long is not an obstacle as long as it is easy to understand.

From now on, we will always use this term in our subsequent articles.

II. Anneng identifies me as a female-judgment method

I believe that some beginners may be confused in this way: they know what is going on with a single name, but once they see the code, they do not know what the name is, so they cannot remember the syntax features of the code. Here, we will introduce you to a simple and easy-to-use method for judging the syntax features.

I believe that some readers have seen the so-called "read from the right to the left" method. The next method is essentially the same as "read from the right to the left, however, both cognition and operation are simpler (at least we think this is the case, so we will not be humble here ). The method is described as follows:

Find * first, and then check *. The right side is the limitation on the pointer p itself, and the left side is the limitation on what p points.

Note: in this article, we refer to p as "things" in general ".

For example

1. const int * p

* There is no restricted component on the right side, indicating that p is a common pointer we are familiar with. The content of p (that is, the value, that is, the address of something it points to) can be changed; * the left side is a const int, indicating that p points to a const int. We cannot modify this int through p because it is a const. (We will explain in detail about "cannot be modified through p)

2.int * const p

* The right side is const, indicating that p itself is const. We cannot modify the content of p (for example, ++ p; it is not acceptable), * the left side is int, that is, p points to a normal int. We can modify it through p (for example, * p = 100; yes ).

3. const int * const p

* The right side is const, indicating that the pointer p itself is const, and * the left side is const int, indicating that the int pointed by p is also const. In this case, p itself cannot be modified, and it cannot be used to modify the int it points.

3. Native use of our products-syntactic features

In fact, when talking about the judgment method, we have already covered their respective syntax features. I will go into some details here.

1. const int * p

Is the so-called "pointer to a constant ". Note that the so-called "pointing to a constant" is only the "wishful thinking" of this pointer, but it is an equivalent effect. In fact, const int * p = & a; a can be both a constant (const int a = 10;) and a variable (int a = 10 ;), however, p is wishful thinking that it refers to a constant, so it cannot be modified by itself, which leads to an equivalent effect-from the perspective of p, it refers to "true" as a constant. Therefore, the best understanding of "pointer to a constant" should be: we cannot use this pointer to modify what it points to (constant or variable ).

Note: const int * p = & a; it means that a cannot be modified through p. If a is not const, you can modify a in other ways (for example, directly ++ ).

In addition, since p itself is only a common pointer, it is allowed not to be initialized during declaration. However, we can only say yes, but do not advocate this. At any time, the pointer should not be non-pointed. If you do not know who to direct a pointer, initialize it to nullptr or NULL (nullptr is a new feature of C ++ 11, which is safer than NULL. This is not detailed here ).

2.int * const p

Is the so-called "itself is a constant pointer ". We have already mentioned that "p itself cannot be modified, but it can be modified by p". Here we will mainly discuss the initialization of p.

Since p itself is const, you must know the value of p during compilation (that is, the address of what p points to). Therefore, you must Initialize p when declaring p. Note that for int * const p = & a, we only require that the address of a is definite, but the value of a can be uncertain. For example, the following code is feasible.

# Include <iostream>

Using namespace std;

Int GetData (int num)
{
Return num;
}

Int main ()
{
Int;
Cin>;
Int B = GetData ();
Int * const p = & B;
Cout <* p <endl;
Return 0;
}


Because int B is declared, the address of B is determined during compilation, but it is clear that the value of B can be determined only when the program is running.

Note that there is no problem in initializing int * const p with nullptr or NULL, because both nullptr and NULL represent valid addresses.

3. const int * const p

It is the so-called "pointer that refers to and itself are constants ". Its syntax is the combination of the first two.

4. Extra articles-about references and const references

This article should have ended, but for C ++, it seems natural to talk about references when it comes to pointers. Then, let's talk about references and const references. The so-called "simple talk" refers to a brief introduction to some principles and details. Why? Because the above concepts will be used in our presentation. In addition, we will only discuss the reference of the left value, that is, the general reference that everyone is familiar with. For the new feature of C ++ 11, the reference of the right value is not discussed.

I believe everyone knows the features referenced.

1. if a reference is bound to an item (the word "thing" is used again here), it will always be an alias for this item ", the alias of another person cannot be added, that is, the reference itself cannot be modified. However, we can modify the value of the referenced item through reference.

2. The declaration must be both initialized and initialized with the left value. (The Left value is the amount of addresses that can be used and evaluated. In other words, there is a certain amount of addresses, rather than the so-called temporary amount)

Are you familiar with these features? Yes, these features are the same as those of "itself a constant pointer" (int * const p. In fact, we can simply use "itself a constant pointer" to understand or even define references:

A reference is a pointer pointing to immutable and automatically unreferenced by the compiler. That is, a reference is a constant pointer automatically referred to by the compiler ".

See the following code.

Int a = 10;
Int & ra =;
Ra = 11;

In the above code, the compiler converts int & ra = a to int * const ra = & a, and ra = 11 to * ra = 11, the process of automatically converting ra to * ra is the "automatic resolution reference" stated in the above definition ".

So what is a const reference (that is, a constant reference, but I want everyone to call it a const reference rather than a constant reference? Apparently, const int & ra = a is equivalent to const int * const ra = &. I believe that the previous explanation is not required.

Postscript:

The following capabilities are limited. Despite the best efforts to be rigorous, mistakes and omissions are inevitable. I urge you to criticize and correct them. Your help is an inexhaustible motive force for moving forward.



Constant pointers and pointer constants in C/C ++

Constant pointer

A constant pointer is a pointer to a constant. The content of the memory address pointed to by the pointer cannot be modified.

The constant pointer defines "const int * p = & a;" to tell the compiler that * p is a constant and * p cannot be used as the left value for operations. But here the pointer p is still a variable, and its content stores the address of the constant, so it is allowed to declare the constant pointer before initialization, and the pointer can also be modified, for example:

Int a = 0, B = 1;
Const int * p; // declare the constant pointer p
P = & a; // p points to
P = & B; // modify the pointer p to point to B.
* P = 2; // not allowed

Pointer constant

A pointer constant is a constant of a pointer that does not change the address. However, you can modify the content it points.

The pointer constant defines "int * const p = & a;" to tell the compiler that p is a constant and cannot be operated as the left value, but can be modified, that is, * p is modifiable. A pointer constant must be initialized at the same time of declaration. It is not allowed to declare a pointer constant first and then assign values to it. This is the same as a normal constant, for example:

Int a = 0, B = 1;
Int * const p1 = &;
Int * const p2; // It is not allowed and must be initialized.
P2 = & B; // not allowed. p2 is a constant and cannot be used as the left value.
* P1 = 2; // The pointer * p1 value can be modified.

If the pointer is used as a function parameter and we don't want to be called to modify the parameter pointer at will, but want to modify the content pointed to by the parameter pointer, we usually take the pointer constant as a parameter. For example:

There are two integer variables a and B. We write a function to exchange the values of a and B. We use the pointer as the form parameter. We do not want the function to modify the value of the parameter pointer, you can set the parameter as a pointer constant. If the function modifies and compiles the pointer, an error is returned.


Void Exchange (int * const a, int * const B)
{
Int temp;
Temp = *;
* A = * B;
* B = temp
}



In fact, if the function does not modify the value of the parameter itself, we generally add const limitation to the parameter, which is also a small trick to improve the code quality. In the class method, if the method does not modify the class attribute value, we usually add const to the method.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.