Correct use of const in C language programming

Source: Internet
Author: User

Basic explanation

Const is a key word in C language. It specifies that a variable cannot be changed. The use of const can be improved to a certain extent.ProgramRobustness, In addition, watching othersCodeIt is helpful to understand the role of Const.

Although this sounds simple, in fact, the use of const is alsoC LanguageWhere are the nuances of a relatively subtle place? See the following questions.

Problem: const variable & Constant

Why does the ansi c compiler report an error when I use a const variable to initialize an array like in the following example?

Const int n = 5;

Int A [n];

Answer and analysis:

1) the difference between "constant" and "Read-Only variable" is discussed. Constants must be read-only, for example, 5, "ABC", etc. They must be read-only, because there is no place in the program to store its value, and of course it cannot be modified. While"Read-Only variable" is to open a place in the memory to store its value, but this value is limited by the compiler and cannot be modified.. C language keywordsConst is a modifier used to restrict a variable from being changed.(Qualifier ). In the above Code, variable N is modified as a read-only variable. Unfortunately, the modification is not a constant. ANSI CWhen an array is defined, the dimension must be "constant" and "Read-Only variables" are not allowed.

2) Note: in ansi c, this writing method is incorrect, because the array size should be a constant, while const int N and n are just a variable (constant! = Immutable variables, but in the Standard C ++, this defines a constant, which is correct). In fact, according to the compilation process and memory allocation, this method should have been reasonable, but ansi c imposes restrictions on arrays.

3) So what are constants defined in ansi c? The answer is:Enum type and # define macro, both of which can be used to define Constants.

Question: content defined by the const variable & Const

The following code compiler reports an error. Which statement is wrong?

TypedefChar* Pstr;

Char String[4] ="ABC";

Const Char* P1 =String;

ConstPstr P2 =String;

P1 ++;

P2 ++;

Answer and analysis:

The problem lies in P2 ++.

1) Basic const format: const char m;

The limit m is unchangeable.

2) Replace M, const char * PM in Formula 1;

The limit * PM is unchangeable. Of course PM is variable. Therefore, P1 ++ is correct in the problem.

3) Replace 1 char, const newtype m;

The limit m is immutable, and the charptr in the problem is a new type. Therefore, P2 is immutable in the problem, and P2 ++ is incorrect.

Problem: const variable & String constant

What is the problem with the following code?

 
Char* P ="I'm hungry!";

P [0] ='I';

Answer and analysis:

The code above may cause invalid memory write operations. The analysis is as follows: "I'm hungry" is essentially a String constantConstants are often put in the read-only memory area by the compiler and cannot be written.. P initially points to this read-only memory zone, whileP [0] = 'I' tries to write this place, And the compiler certainly does not agree.

Problem: const variable & String constant 2

Is char a [3] = "ABC" Legal? What are the risks of using it?

Answer and analysis:

This is legal in Standard C, but its living environment is very small; it defines an array of 3, initialized as "ABC", note, it does not have the usual string Terminator '\ 0', so this array only looks like a string in C language, but it is not actually, so all functions that process the string, for example, strcpy and printf cannot be used on this fake string.

Problem: const & pointer

In the type declaration, const is used to modify a constant. There are two ways to write it. So, what are the following statements that use const to limit immutable content?

 1 ) Const is in front

Const Int Nvalue; // Nvalue is const

Const Char * Pcontent; // * Pcontent is const, and Pcontent is variable.

Const ( Char *) Pcontent; // Pcontent is const, * Pcontent is variable

Char * Const Pcontent; // Pcontent is const, * Pcontent is variable

Const Char * Const Pcontent; // Both Pcontent and * Pcontent are const

2 ) Const is behind and equal to the above declaration

Int Const Nvalue; // Nvalue is const

Char Const * Pcontent; // * Pcontent is const, and Pcontent is variable.

( Char *) Const Pcontent; // Pcontent is const, * Pcontent is variable

Char * Const Pcontent; // Pcontent is const, * Pcontent is variable

Char Const * Const Pcontent; // Both Pcontent and * Pcontent are const

Answer and analysis:

Using const and pointer together is a common confusion in C language. In actual development, especially when looking at other people's code, it is often difficult to judge the author's intention because of this, the following describes my judgment principles:

Draw a line along the line *. If the const is on one side, then the const is the element limited by the const. You can view the actual meaning of the above statement based on this rule, and I believe it will be clear at a glance.

Note:For const (char *); Because char * is a whole, it is equivalent to a type (such as char), so this is to limit the pointer to 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.