Common modifiers const in C ++

Source: Internet
Author: User

ConstYesC ++It is a frequently-used type modifier, But I found at work that many people only take it for granted. In this way, sometimes it is used correctly, but in some subtle occasions, I am not so lucky. The reason is mostly because I have not figured out the source. Therefore, in this article, I will analyze const. Trace its source and investigate its essence, hoping to help you understand const. Based on the undertaking relationship of thinking, this article will be divided into the following parts.

Why is const introduced in c ++?

The c ++ creator introduced or retained the const keyword based on the purpose ?, This is an interesting and useful topic and is helpful for understanding const.

1. as we all know, c ++ has a strict type compilation system, which allows many errors of c ++ programs to be found in the compilation stage, greatly reducing the error rate, it has also become an outstanding advantage in comparison with c ++.

2. A common preprocessing command # define variablename variablevalue in c can be easily used for value substitution. This value substitution has at least three advantages:

The first is to avoid the appearance of numbers with vague meanings, so that the program semantics is fluent and clear, as shown in the following example:
 

# Define user_num_max 107 avoids the confusion caused by using 107 directly.

Second, you can easily adjust and modify parameters. In the preceding example, when the number of people changes from 107 to 201, you can modify the parameters here,

Third, it improves the execution efficiency of the program. Because the pre-compiler is used for value substitution, it does not need to allocate storage space for these constants, so the execution efficiency is high.

In view of the above advantages, the use of such predefined commands is everywhere in the program.

3. Speaking of this, you may be confused about the relationship between the first and second points and const ?, Okay. Next, let's look at it:

The pre-processing statement has many advantages, but it has a fatal disadvantage, that is, the pre-processing statement is only a replacement of simple values and lacks a type detection mechanism. In this way, the pre-processing statement cannot enjoy the advantage of strict c ++ type checks, which may cause a series of errors.

4. Now, the first stage has come to the conclusion:

Conclusion: The initial purpose of const is to replace precompiled commands, eliminate its disadvantages, and inherit its advantages.

Now its form is changed:

 
 
  1. const datatype variablename = variablevalue ; 

Why can const replace predefined statements?

What is the magical power of const so that it can shake its arm to replace the predefined statement?

1. First, the constant value modified by const is non-mutable, which is the basis for replacing predefine statements.

2. Second, it is obvious that it can also avoid the appearance of numbers with vague meanings, and it is also convenient to adjust and modify parameters.

3. third, the c ++ compiler usually saves them in the symbol table instead of allocating storage space for common const constants, which makes them a constant during compilation, without the storage and read memory operations, the efficiency is also very high. At the same time, this is also an important basis for replacing predefine statements.

Here, I would like to mention why this is also the basis for it to replace the pre-defined statements, because the compiler will not read the stored content, if the compiler allocates storage space for const, it cannot be a constant during compilation.

4. Finally, the const definition is like a normal variable definition. It will be checked by the compiler for its type, eliminating the hidden danger of predefine statements.

Classification of const usage

1. const is used for Pointer Analysis in two cases:

 
 
  1. Int const * a; file: // a variable, * a variable
  2. Int * const a; file: // a is not variable, * a is variable

Analysis: const is a type modifier that is left-bound. It is the type Modifier on its left and a type modifier. Therefore, int const is limited to * a, not limited to. Int * const limits a, not *.

2. const limits the passing value parameters of the function:

 
 
  1. void fun(const int var); 

Analysis: The preceding statement specifies that parameters cannot be changed in the function body. According to the characteristics of value transfer, the changes of var in the function body do not affect the function exterior. Therefore, this limitation has nothing to do with the function user and is only related to the function writer.

Conclusion: It is best to limit the internal function to block external callers to avoid confusion. The following code can be rewritten:

 
 
  1. void fun(int var){  
  2. const int & varalias = var;  
  3. varalias ....  
  4. .....  

3. const limits the return value of the function:

 
 
  1. const int fun1();  
  2. const myclass fun2(); 

Analysis: The above statement limits that the return value of the function cannot be updated. When the function returns an internal type such as fun1), it is already a numerical value. Of course, it cannot be updated by value assignment, at this time, const is meaningless. It is best to remove it to avoid confusion. When the function returns a custom type such as fun2), this type still contains variable members that can be assigned values, so it makes sense at this time.

4. Transfer and return address: This is the most common case. It can be seen from the characteristics of address variables that the appropriate use of const is significant.

5. const qualified class member functions:

 
 
  1. class classname {  
  2. public:  
  3. int fun() const;  
  4.  .....  

Note: This post-const form is a provision to avoid confusion. Use const in the declaration and definition of this function, because const has become part of the type information.

Ability to obtain: constant objects can be operated.

Capacity Loss: you cannot modify the data members of a class or call other functions that are not const in a function.

In this article, I am not talking much about const, because I don't want to turn it into a c ++ textbook. I just want to elaborate on its essence and usage in detail. I will try to explain it in detail, because I hope to express some of my thoughts in a very relaxed and casual atmosphere. After all, programming is also part of a relaxed and happy life. Sometimes, you may wonder that the world is so beautiful.

We hope that the above content will help 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.