Const (1) in C ++)

Source: Internet
Author: User

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

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.