Const usage lizi2

Source: Internet
Author: User

Const is used to protect program robustness and reduce program risks.
The usage of const is complicated. It can be summarized as follows:
1: used when defining variables:

A: const int a = 100; the simplest usage means that variable a is a constant variable;
B: int const B = 100; same as;
C: const int * a = & B; pointer to a constant, that is, the value of the pointer itself is OK.
Changed, but the content pointed to cannot be changed;
D: int const * a = & B; same function as c;
E: int * const a = & B; constant pointer, that is, the value of the pointer itself cannot be changed,
However, the content to be pointed to can be changed;
F: const int * const a = & B; a constant pointer to a constant, that is, the pointer and
The content to be pointed to cannot be changed;
G: const int & a = 100; constant reference, that is, the reference value cannot be changed;

Conclusion: initialization is required when you use const to define variables.
Mark (*, &) indicates the content to be directed to on the left, and on the right, indicates itself.

2: Used in functions:

A: void func (const int a); used as a parameter, it indicates that the function body is not
This parameter can be modified. For different formats when no parameter is defined, see defining variables.
Usage;
B: const int func (); used as the return value, indicating that the return value of the function is not
If it can be modified, apply const int a = func () when obtaining the return value;
Parameters are defined in different forms. For more information, see How to Use variables;
C: int func () const; a regular function, which indicates that a function cannot modify a member of a class.
Value, which can only be used in member functions of the class;

Conclusion: Using const in a function is similar to defining variables.

The above is a bit of work experience. please correct me if you have any errors! Thank you!

 

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.