Const modifier Brief

Source: Internet
Author: User

Use of 1.const qualifiers

1) Define Const constants: Const can change an object to a constant, not modifiable (read-only type), and must be initialized at the time of definition. For example:

Const double mathpi = 3.141592653;

2) The parameters of the modifier function, the return value, and so on. Things that are modified by the const will no longer change;

3) If you are using variables from other files throughout your program:

If the variable is non-const//file_1.cppint months = 10;//file_2.cppextern int months;//const modified variable//file_1.cppextern const INT Dayperyear = 365;//file_2.cppextern const int dayperyear;

2. Pointer constant-constant pointer

1) Const int * P1: constant pointer (modifier type: pointer to read-only type)

2) int * Const P2: pointer constant (modifier pointer: constant of pointer type)

3) const int* Const P3: pointer constant pointing to constant

constant pointer: You can point to a constant or to a variable, you can change the point, but you cannot change the value of the point to the content;

Pointer constants: Must be initialized, constants cannot be assigned values. Pointers cannot be changed to point, and can be modified by pointers to the values in memory;

Constant pointer to constant: cannot change direction or modify content

3.CONST and macro define the difference between # define #

You can use const to define constants in C + +, or you can define constants by using # #:

1) The const constant is a data type, and the macro definition constant does not have a data type, so the compiler can perform type safety checks on the former and only character substitution for the latter;

2) const constants can limit the definition of a variable to a specific function or file, whereas a macro definition can only be in the head of a file;

3) const can be used for more complex types, such as arrays, structs, and classes.

Const modifier Description

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.