Const usage Summary

Source: Internet
Author: User

1. Const type variables must be initialized during Declaration; otherwise, an error will be reported.

2. Define a non-const object in the global scope, which can be accessed throughout the program
For example:
// File1.cc
Int counter;
// File2.cc
Extern int counter;
++ Counter;

Defining the const variable in the global scope means that this variable is a local variable of the file. You must specify the variable type as extern to use this variable throughout the program.
For example:
// File1.cc
Extern const int counter = 0;
// File2.cc
Extern const int counter;
++ Counter;

3. Const application and non-const reference
A non-const reference can only be bound to a variable of the same type as the reference, and cannot be initialized to the right value.
For example:
Double A = 1.22;
Int & B = A; // Error
Double & C = A; // correct
Int r = 10;
Int & D = R + 55; // Error
Because the compiler will convert the Code:
Int temp =;
Int & B = temp;
That is to say, B is not bound to A, but to temp. It is impossible to change a through B, so this is illegal.

The const reference can be bound to different types or the right value.
For example:
Double A = 1.22;
Const Int & B = A; // correct
Const double & C = A; // correct
Int r = 10;
Const Int & D = R + 55; // correct

4. pointer to const
For example:
Double A = 1.01;
Const double * B = &;
* B = 2.1; // This is obviously incorrect.
A = 2.1; // This is correct. The values of A and * B are both 2.01. Some people call it a pointer to const.

5. Const pointer
For example:
Int A = 10;
Int * const B = & A; // This means that B can only point to
A = 20;
* B = 30; // The value of the variable can be changed in the preceding two statements.

It is also related to Article 4 and interesting:
Typedef int * pint;
Int value = 10;
Const pint a = & value;
Pint const B = & value;
Int * const c = & value; // The effect of the three statements is consistent.

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.