Keyword of c -- const's understanding and usage

Source: Internet
Author: User
Keyword of c -- const comprehension and usage Author: lj_860603 views: 21106 Article Source: site original Release Date:-7-1 Comments (21)

Enter the original post discussion: http://bbs.bccn.net/thread-66030-1-1.html

Understanding and usage of const, the keyword of C

The usage of const in C is flexible (I believe C ++ is also the same). I personally feel that I love and hate it. Sometimes I feel that const is easy to use and

Mistakes are often made because of its advantages. In addition to carelessness, the other more important reason is that the previous understanding of const is not in place. So today

Write a small summary by yourself. If you are a beginner, it is recommended to take a good look. I believe it will help you a lot. If you are a master, please don't hesitate to give us a try!

I wrote a piece of nonsense above, even in a small order :) The following is the text;

1. Specific Definition of const:

-- I personally feel that it is difficult to define the next standard. Because of its flexible usage, it seems that people cannot understand its definition.

Meaning, and it is easy to misunderstand (maybe the level is too good ). For example, define a variable as a constant that cannot be modified.

Keyword. In this case, we may misunderstand that the variable cannot be modified as long as const is in the defined variable. This

This is a one-sided understanding (we will discuss this issue in the following usage ). Therefore, I am afraid to define it here, and other reference books do not seem to have

Is defined.

II. Specific functions of const
-- The function of const is flexible. If the position of const in an expression is different, the effect may be different. Details are as follows:

Analysis (Of course, not all cases are covered)
A. The most common usage of const
1. To prevent the passed function parameters from being modified, use the const keyword in the called function parameters.
// Example->

Int findnum (const int array [], int num, int conut); // declare a function

// Code...

Int findnum (const int array [], int num, int count)
{
Int I;
Int flag = 1;

For (I = 0; (I <count) & flag; I ++)
{
If (array [I] = num)
{
Flag = 0;
Break;
}
}
Return flag;
}
// Code...

In the preceding example, the compiler treats array [] as an array of constant data. So, if you accidentally assign values to the array

The compiler reports an error. Therefore, when you do not need or want to modify the data of the array, it is best to use const to define the array as a constant array.

2. const can be used to create array constants, pointer constants, and pointers to constants:
Const char CH = 'a ';
Const int A [5] = {1, 2, 3, 4, 5 };
Const int * P = A; // A is the first address of an array. P is the pointer to a constant.
Int * const P = A; // A is the first address of an array. P is a pointer constant;
Const int * const P = A; // A is the first address of an array. P is a pointer constant pointing to a constant.

The first two cases are very simple. Now I want to analyze the last three cases, because these three cases are prone to errors, and sometimes I am afraid of mistakes.

The const is not required.

-- Const int * P = A; // P is a pointer to a constant. Therefore, you cannot assign a value to the pointer to change the array.

//, For example:
// * P = 10;/* Error */
// * (P + 2) = 1;/* Error */

// If the constant pointer can change the value, the value also changes the number of arrays.

// Data. If you do not understand it, you may find a way to understand it.

// If a person is bound together, maybe you have moved the position and he does not move it with you! Haha

-- Int * const P = A; // check this expression. The position of const is different from that of the first one! Their usage and functions

// It's totally different. At this time, P is a pointer constant. We know that the pointer is pointing

// The first address of an array, so its location cannot be changed. But you

// Now it should be compared with the first expression. The current array is not a constant array,

// The array data can be changed, but the pointer cannot be moved at this time.

//, Pointing to the first data in the array, so it can and can only change the first data in the array

// Data value. Do not misunderstand this. The pointer constant is that its address cannot be changed.

// The content that it does not point to cannot be changed. Remember this!

// Okay. If you do not understand it, another example of a comparative image is provided to illustrate:

// If a fixed person pulls another person's hand, note that the fixed person is equivalent

// Cannot be replaced by another person. But he can hold others' hands,

// It is not necessarily stipulated that he must pull the same person's hand. Now you should have a ratio

// Have a deep impression and understanding: P

// The following examples help you understand the problem:
// * P = 2;/* Yes */
// * (P + 1) = 10;/* Yes */
// P ++;/* No */

-- Const int * const P = A; // if you understand the essence of the first two expressions, you can understand the basics of this expression.

// No problem. There are two const, and the position of one const is the first one.

// The Position of the condition. The second const is the position of the second condition.

// This is the sum of the functions of the first two cases. Not much to mention here!

// The following examples help you understand the problem:
// * P = 2;/* No */
// * (P + 2) = 10;/* No */
// P ++;/* No */

B. Const does not prevent parameter modification.

The reason for this is that some friends may think that using const in function parameters will not change.

This is actually an incorrect understanding of the parameter, because it does not prevent modification of the parameter. The following is a simple example;

# Include <stdio. h>
# Include <ctype. h>

Void changestr (const char * string );

Int main (void)
{
Char STR [] = "the C programme ";

Change (STR );
Printf (STR );

System ("pause ");
Return 0;
}

Void changestr (const char * string)
{
Char * Source = (char *) string;

While (* Source)
{
* Source = toupper (* Source );
Source ++;
}
}

// End

The above program converts every character in the string into uppercase letters. Because * string gives the address to * source, and

* Changing the value of source does not interfere with the compiler. Some compilers may issue warnings. The above program is only used to indicate that const will not stop

The modification of parameters will make people easy to get confused if they feel meaningless like the above program.

I can only say so much about the usage and understanding of Const. Of course, there may be more advanced or less useful usage.

And limited experience.

Iii. References
-- C primer plus 5th

ID: lj_860603
Organized on 2006.5.21

 

 

Article entry: static thinking, responsible editor: static thinking
  • Previous Article: Author: Unknown
    Updated on: 18:48:16 "> interoperability between arrays and pointers in C Language
  • Next article: Author: Zhang Xiaoxiang
    Updated on: 15:48:48 "> I can definitely test your C language skill.


  • Latest comment:Existing21Readers who are interested have made comments

    BCCN usersIP: 210.14.76. * published at 23:51:31, 2009-1-9

    I compiled it with vc6.0, But I commented out the sentence "system (" pause ");" and output the correct result after execution.

    BCCN usersIP: 116.24.167.*0:21:39

    He
    The last example is that, if there is a problem, it can be compiled in C because the variable processing in C is not very strict, it is precisely because of this that the C code may contain many hidden errors that the compiler cannot detect.
    Good. The type check of variables in C ++ is very strict. Therefore, if your last variable is compiled using the C ++ compiler, it cannot be compiled. In addition, we forcibly copy a constant pointer to a constant pointer.
    This is itself an undesirable practice, which violates the intention of using Const.

    BCCN usersIP: 219.128.252.*9:42:22

    Good

    BCCN usersIP: 218.205.238.*0:03:27

    Int * const P = A this also says that only the value of the first data of the data can be changed, and the address cannot be changed, but the value pointed to by the address can be changed, why can't we change the value of the first data?

    BCCN usersIP: 60.186.218.*15:15:49

    Const char * string is wrong
    According to what you want to explain, it should be char * const string.

    BCCN usersIP: 121.31.145.*18:44:08

    My compiler doesn't work. Why?

    BCCN usersIP: 59.83.75.*17:17:13

    1213

    BCCN usersIP: 123.191.80.*14:26:11

    Is there any details? If you have any gains, is it very detailed?

    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.