Limitations of const

Source: Internet
Author: User

Once a const object is created, its value cannot be changed, so the const object must be initialized . Compared to non-const types, the main difference is that the Const type object executes but does not change its operation content.

By default, const is only valid within a file. By default, the const-defined object is limited to the file class, and when a const with the same name appears in multiple files, it is equivalent to having separate variables defined separately in different files. So we only define the const object in one file, and in other files we just declare it. The extern keyword is added to the const object, whether it is a declaration or a definition, so it needs to be defined only once . As follows:

Define I in the File1.h file

extern const int i=3; Define I as a constant 3

When you refer to I in file2.h, just declare it and avoid redefining it.

extern const int i;

int a=i; So you can use I.

A const reference is referred to as a reference to a constant (reference to const), the reference type must be consistent with the object it refers to, but there are two exceptions, with the first exception being to allow arbitrary expressions to be used as initial values when initializing a constant reference . Allows the binding of a const object, a literal value, or even an expression, for a constant reference:

int i=42;

const INT &r1=i; Correct, at this time R1 and I bind

const INT &r2=42; Correct, bind a literal at this time 42

const INT &r3=r1*2; Correct, R3 is a constant reference, bound literal 84

int &r4=42; Error, non-binding literal value of very much reference

Limitations of 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.