Const usage in C ++ and const usage

Source: Internet
Author: User

Const usage in C ++ and const usage

1 const int a; 2 int const B; // same as 3 // 4 const int * c; // const modifies the data of the memory space d pointed to by the pointer, 5 int * const d cannot be modified;/* d Regular pointer (the pointer variable cannot be modified (d cannot be changed), but the memory space it points to can be modified) */6 const int * const e; // the pointer and the memory space it points to cannot be modified.

The const in C language is not a const in the true sense. in C language, the const variable is a read-only variable and has its own storage space. In C language, the value of a can still be changed by indirect value assignment.

Void main () {// It seems that a is a constant const int a = 10; // a = 11; int * p = NULL; p = (int *) &; * p = 20; // indirect value: printf ("a: % d \ n", a); printf ("* p: % d \ n", * p ); system ("pause ");}

In fact, in C ++, const creates a symbol table. When the pointer is used for indirect value assignment, a memory space will be re-opened. The value of indirect modification of a is only modified, and the value of new memory space will be re-opened, it has nothing to do with the value of a in the original symbol table.

Therefore, const in C ++ is the true const.

Const in C ++ is a real constant instead of a variable (read-only) in C ). It has been determined during the const modified constant compilation.

 

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.