What does the const modifier mean to convert an object to a constant object?
The value of a variable that is decorated with a const can no longer be modified anywhere in the program, just like constant use!
The use method is:
const int A=1;//here defines a const constant variable a of type int;
But as far as the pointer is concerned, the const still works, and here are two things to be very careful about, because the following two questions are easy to confuse!
Let's take a look at one of the following examples:
#include <iostream>
using namespace Std;
void Main (void)
{
const int a=10;
int b=20;
const int *PI;
pi=&a;
cout <<*pi << "|" << a <<endl;
pi=&b;
cout <<*pi << "|" <<b <<endl;
Cin.get ();
}
The most important sentence in the above code is the const int *PI
This sentence reads from the right seat: Pi is a pointer to an int type, defined as a const object;
The function of such a declarative method is to modify the memory address that the PI pointer points to, but not to modify the value of the object pointing to it;
If you add *pi=10 to the code, such an assignment is not allowed to compile!
OK, look at the above two examples you have a basic understanding of the const, then we look at a very easy to confuse usage!
See the following code:
#include <iostream>
using namespace Std;
void Main (void)
{
int a=10;
const INT *const pi=&a;
cout <<*pi << "|" <<a <<endl;
Cin.get ();
}
The most important sentence in the above code is the const int *const pi
This sentence reads from the right seat: pi is a const pointer to an int type object;
The effect of such a declaration is that you can neither modify the memory address of the object to which pi is pointing nor modify the value of the object by the way of the pointer's dereference, that is, by *pi=10;
So if you add *pi=20 at the end, trying to modify the value of object A in this way is not allowed to compile!
Combined with the above two points said, the code can be modified to the following form will be necessary in the program anywhere to modify the value of object A or the address of the pointer Pi, the following type of writing is often used as the form of the number of parameters, so as to ensure that the object will not be changed in the number of the culvert!
#include <iostream>
using namespace Std;
void Main (void)
{
const int a=10;//This sentence is different from the above, please note!
const INT *const pi=&a;
cout <<*pi << "|" <<a <<endl;
Cin.get ();
}