Const_cast in C ++

Source: Internet
Author: User
# Include <iostream>
# Include <string>
Using namespace STD;
Int main ()
{
Const int num = 1;
Int * P = const_cast <int *> (& num );
* P = 2;
Cout <num <Endl; // output 1
Cout <* P <Endl; // output 2
// But & num and P are the same. Why?
Cout <& num <Endl;
Cout <p <Endl;
}

Question added:

I want to emphasize why the pointer P and & num are the same, but * P is different from num. How can there be two different values for the same address?

Answer:
C ++ usually does not allocate storage space for const!
Instead, the definition is saved in the symbol table. In addition, it is initialized when you enter the symbol table. In this example, the value of the symbol num will always be 1.

The use of pointers (take the address) is to forcibly allocate space! However, the result is not the same as the previous Const. Although space is forcibly allocatedProgramThe const in the symbol table is still used.

C ++ is flexible enough!

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.