A detailed explanation of const usage in C + +

Source: Internet
Author: User

Object-oriented is an important feature of C + +.

But C + + on the basis of a new increase in the number of optimization is also very dazzling on the const directly can replace C in the #define the following points are very important, learning bad consequences are also very serious

Const

1. Qualifier declaration variable can only be read

const int i=5;

int j=0;

......

I=J//illegal, resulting in compilation errors

j=i;//Legal

2. Must initialize

const int i=5;//Legal

const int J;//Illegal, causing compilation errors

3. Referring to the const constant in another connection file

extern const int i;/Legal

extern const int j=10;//illegal, constants cannot be assigned again

4. Easy to type check

Use the Const method to make the compiler more aware of what is being handled.

#define I=10

Const LONG &i=10;/*dapingguo reminder: Because of compiler optimizations, I do not allocate memory when Const long i=10, but have 10 directly into subsequent references so that there are no errors in future code, especially for the purposes of preaching. &i explicitly gives the memory allocation of I. However, once you turn off all optimizations, even a const long i=10 can cause subsequent compilation errors. */

char h=i;//Nothing wrong

Char h=i//compilation warning, which may result in incorrect assignment due to a truncated number.

5. Can avoid unnecessary memory allocation

#define STRING "Abcdefghijklmnn"

const char string[]= "ABCDEFGHIJKLMN";

......

printf (string);//Assigned first memory to STRING

printf (string);//Allocate memory once for string, no longer assigned

......

printf (string);//allocated second memory for STRING

printf (string);

......

Because the const definition constant is given a corresponding memory address from the assembly point of view, rather than giving an immediate number like #define, the const-defined constant has only one copy during the program's operation, while the #define-defined constant has several copies in memory.

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.