Const of const and C ++ is a very troublesome keyword, but if you don't need it, it will also cause some trouble.
The following section is simple:ProgramDemonstrate the wonderful relationship between the const variable and the const pointer
1 # Include " Stdafx. h "
2
3
4 Int _ Tmain ( Int Argc, _ tchar * Argv [])
5 {
6 Const Int Constint1 = 1 ;
7
8 Const Int * Constintpoint = NULL;
9
10 Int * Intpoint = NULL;
11
12 Constintpoint = & Constint1;
13
14 Const Int Constint2 = 2 ;
15
16 Int Int3 = 3 ;
17
18 // Intpoint = & constint2; // Error 1
19
20
21 Constintpoint = & Int3;
22
23 // (* Constintpoint) ++; // Error 2
24
25 Printf ( " Constint1 = % d \ r \ n " , Constint1 );
26 Printf ( " Constint2 = % d \ r \ n " , Constint2 );
27 Printf ( " Int3 = % d \ r \ n " , Int3 );
28
29 Printf ( " Constintpoint point to % d \ r \ n " , * Constintpoint );
30 Return 0 ;
31 }
32
33
The simplest and clearest way to use const is to declare the const variable. The variable needs to be initialized immediately in the place of life, and cannot be changed after initialization.
If you look at the const pointer in the same way, you will find that your mistake is very serious. You see, this constintpoint is still quite cool with a few goals, and the compiler happily accepts this section.Code, Not even warn.
The original const pointer is a pointer to the const variable, rather than the pointer itself is a const. None
OK, the const variable cannot be modified directly. Can't I get his address and modify it again? No, the compiler will tell you that a const pointer cannot be converted into a common pointer,
Error 1 error c2440: '=': cannot convert from 'const int * _ w64' to 'int *'
Whether a variable is declared as const or not, you can point to it with a const pointer, and then use the * operator to retrieve the variable and try to modify it, see error2 commented out in the Code.
Error 2 error c3892: 'confintpoint': you cannot assign to a variable that is const