Const usage in C language

Source: Internet
Author: User

One, possible combinations:

(1) Const CHAR*P

(2) Char Const*p

(3) Char *const p

(4) const char **P

(5) Char Const**p

(6) Char *const *p

(7) Char **const p

Of course, in (5), (6), (7) and then insert a const in a number of cases, but the analysis of the above 7, the other can be analogy!

Second, understand the key to help remember:

1, the key to see the const modification who.

2, because there is no const * operation, if there is a const * form, then the const is actually decorated in front. For example: Char Const*p, because there is no const* operation, the const is actually decorated with the preceding char, so char const*p is equivalent to the const char*p. That is to say, (1) and (2) are equivalent in the above 7 cases. Similarly, (4) and (5) are equivalent. In (6), because there is no const* operation, the const actually modifies the preceding char*, but cannot be converted to a const (char *) *p at the time of definition, since the definition is "()" is the representation function.

Iii. in-depth understanding of 7 combinations

(0) The space that is opened up by the program at execution time is in memory (RAM), while the memory unit in RAM is readable and writable; The pointer is just a tool to specify or locate the data to be manipulated, just to read and write the working pointer of the memory unit in RAM. If the pointer is not qualified, a pointer in the program can point to any location in RAM (except for system sensitive areas, such as the area of the operating system kernel) and read and write to the memory unit it points to (determined by the ram's readable writable property) The readable writable properties of memory units in RAM are not changed by the qualification of the working pointers (see 4th below), and all the various const qualifiers on pointers are simply qualified to read and write access to the pointer, including the read-write location.

(1) Char *p:p is a working pointer that can be used to read and write to any location (non-system sensitive area), one byte at a time (char takes one byte).

(2) const char*p or char const *P (because there is no const*p operation, so the const modifier is the preceding char): "Read-only" operations can be performed on any location (non-system sensitive area). ("Read Only" is the content that is qualified relative to char *p)

(3) Char *const p (const-modified P): Read and write only to "one fixed location" and must be initialized when P is defined (because "p=" cannot be performed later.) , so it cannot be initialized later, so it can only be initialized at the time of definition. ("A fixed position" is defined in relation to char *p) can summarize the above 3 points: the pointer p in Char *p is usually a "magnum" working Pointer, while (2) and (3) add some specific restrictions on the basis of (1), which are not required in the program, Just to prevent the programmer's carelessness and produce the wrong error. Also, be aware that "every memory space can have a name, and that the contents of each block of memory are variable (unless limited)". For example, the function defines the char s[]= "Hello", in fact, in the process of the stack memory opened 6 variables a total of 6 bytes of space, where the names of 6 character variables are: s1[0], s1[1], s1[2], s1[3], s1[4], s1[5] (content is ' + ') {To be verified: There is also a 4-byte pointer variable s. However, S is "limited", is a char *const type, which is said earlier (3) This case, S has been pointing to s[0], ie (*s==s[0]== ' h '), can be *s= ' k ' to change the value of S point to s[0], but cannot execute (char *h= " AAA "; s=h;) to assign a value to s in addition. }

(4) above (2) and (3) only P is limited, there is no limit to the space pointed to P, for "char s[]=" Hello ", const char*p=s;" Although the array element cannot be modified by * (p+i) = ' x ' or p[i]= ' x ' s[0 ]~S[4], but can be modified by * (s+i) = ' x ' or s[i]= ' x ' to modify the value of the original array element the readable writable property of the memory unit in the--ram is not changed by the qualification of the working pointer, but only by its own qualification. such as the const char c= ' A ', C is the name of a memory cell (8 bytes) in RAM, the contents of which are only readable and not writable.

(5) const char **p or char const**p: involves two pointers p and *p. Because of the const modifier char, there is no qualification for pointer p, and the pointer *p is limited to the above case (2).

(6) Char *const *p: involves two pointers p and *p. Because the const modifier precedes the char*, that is, the content pointed to by P *p is qualified (also belongs to the preceding case (2)). For *p, because it cannot be assigned by "*p= ...", it belongs to the qualification of the preceding case (3).

(7) Char **const P: involves two pointers p and *p,const modifier p, the upper case (3) is limited to p, and there is no qualification for *p.

Iv. type compatibility issues with Char **p, const char **P

1, problem char *p1;const *p2=p1;//legal char **p1;const char**p2=p1;//illegal, there will be warning warning:initialization from incompatible pointer t ype Char **p1;char const**p2=p1;//Illegal, there will be a warning warning:initialization from incompatible pointer type CHAR**P1;CHAR*CONST*P2 =p1;//Legal

2, the judgment Rule definite Const modification Object! For pointer P1, and P2, to make p2=p1, it can be read: "P1 is a pointer to the X type, and P2 is a pointer to the X type with const qualification". As long as the X type is the same, it is legal. Char *p1;const *p2=p1;//Legal: P1 is a pointer to a (char) type, and P2 is a pointer to the (char) type with const qualification. Char **p1;const char**p2=p1;//is illegal: P1 is a pointer to a (char*) type, and P2 is a pointer to ((const char) *) type. Char **p1;char const**p2=p1;//illegal; char**p1;char*const*p2=p1;//Legal: P1 is a pointer to the (char *) type, and P2 is a pointer to the (char*) type with const qualification.

V. Other

1. Unified reading with const single or double pointer: "P is a pointer, is a [" with a const-qualified "] pointer to [" with the const-qualified "]x type of pointers". L For example: const char* Const *P is said to be: P is a const-qualified pointer to a const-qualified (char*) type.

2, the definition of the const-modified object is determined, but not in the definition of parentheses, or the definition with "()" in the expression of the function type is confused! Therefore, the definition cannot be written (char *) const *P or (const char) **p.

Vi. issues (due to post-blog message there is a limit on the number of characters, the reply moved to here) Question 1 (see post Post): The explanation is very good, but there is a question to explore: For example: const char wang[]={"Wang"}; Char *p; P=wang; Is wrong. So p in Char *p cannot point to a constant variable. (1) need to be supplemented and corrected. Reply: Hello! Thank you for correcting me! I did the following tests under the Ubuntu 10.04 (gcc 4.4.3)://test_const.c #include int main () {const char wang[]={"Wang"}; char *p; p=wang; p[2]= ' C '; printf ("P is%s\n", p); return 0; } Compile: Gcc-o test_const test_const.c output is as follows: Test_const.c:in function ' main ': Test_const.c:17:warning:assignment Discar DS qualifiers from pointer target type executes:./test_const P is WACG

Conclusion: According to the 4th-compatibility problem of this blog post, it is illegal to assign the const-type Wang to P. However, the compiler's handling of it is only a warning, so the data for the read-only region is modified by p at execution time. This should be the result of the compiler processing lax, I do not know what compiler you use? Question 2 answers http://www.linuxsir.org/bbs/showthread.php?t=239058 mentioned questions in C language//test.c int main () {const char* S1 = "Test"; cha R *s2 = S1; S2 = "It ' s modified!"; printf ("%s\n", S1); } out:it ' s modified!; Is that OK? According to my understanding is not the Const qualifier in C language is only a display of one?

Reply:

(1) First, the above code compiles with an error warning:initialization discards qualifiers from the pointer target type, because char *s2 = S1 and problem 1 mentioned, do not conform to the compatibility rules.

(2) The output is correct, the code analysis is as follows: int main () {const char* S1 = "Test";////In the read-only data area (Rodata area after objdump-h test) Open 5 bytes to store "test" and use S1 to point to the first character ' t '. char *s2 = S1; The S2 also points to the first character ' t ' of the ' test ' in the read-only data area. S2 = "It ' s modified!"; Open 15 bytes of storage "It's modified!" in the read-only data area and point S2 from ' t ' to ' it's modified! ' The first character ' I '. printf ("%s\n", S1); Output the string "test" from the ' t ' indicated by S1. }

(3) Summary: The misunderstanding of the questioner is, mistakenly think s2 = "It's modified!" is the re-assignment of the "Test" area, in fact, this is just the "universal" work pointer S2 point to another newly opened area. For example, if you execute s2[2]= ' a ' after char *s2 = S1, the area of "Test" is written, and a segment error occurs when executing. But this error is actually not related to const, because the "test" area itself is read-only. To prevent errors in understanding, everything is assigned to pointers (such as S2 = "It's modified!"), then read them: Point S2 to "it's modified! "The first character in the area.

(4) Bonus: After executing gcc-o test test.c, "test", "It's modified!", "%s\n" are stored as string constants in the read-only region (. rodata) of the binary test. In fact, when a program is compiled to run, the variable space is allocated in the following cases:

A, the assigned global variable or the static variable = = is placed in the executable file's. Data segment.

B, unassigned global variable or static variable = = is placed in the. BSS segment of the executable file.

C, the string constants appearing in the code or the a=> of the const are placed in the. Rodata segment of the executable file.

D, the general local variable = = does not occupy space in the executable file, and allocates the stack space for the binary file when it is running in memory as a process.

E, the variable of malloc or new in the Code = = does not occupy space in the executable file, and allocates heap space for the binary when it is running in memory as a process. Question 3: (For further analysis) verify that Boven (3) refers to the allocation of space for S, the preliminary analysis results are: not assigned! S is just the s[0] address of the code.

#include <stdio.h>
intMain ()
{intA=3;
CharS1[] ="Test";
intb=4;
CharS2[] ="test2";
printf"The address of A is%u\n", &a);
printf"S1 is%u\n", S1);
printf"The address of S1 is%u\n", &AMP;S1);
printf"The address of B is%u\n", &b);
printf"S2 is%u\n", S2);
printf"The address of S2 is%u\n", &AMP;S2);
}

Output result: The address of A is 3213037836

S1 is 3213037827

The address of S1 is 3213037827

The address of B is 3213037832

S2 is 3213037821

The address of S2 is 3213037821

As you can see from the results, the compiler did some optimizations.

Vii. Other relevant classic articles reproduced Allan H.N. Wang, huaqing Vision Embedded College lecturer, the understanding of the Const keyword http://www.embedu.org/Column/Column311.htm is currently in C language tuition, It is found that many students have a great misunderstanding about the key word of Const. Now summarize the misunderstanding of this keyword understanding, I hope in the future programming, the flexibility to use the keyword of the const.

1, const modified variable is a constant or variable for this problem, many students think that the const modified variable can not be changed, the result is mistaken that the variable becomes a constant. So how does the const-modified variable understand that? Let's look at an example:

int main ()

{

Char buf[4];

const int a = 0;

A = 10;

}

This is easier to understand, the compiler directly error, because of "a = 10;" This sentence, the const modified variable, followed by the assignment operation. This seems to indicate that the const modifier's variable cannot be modified, and that is not the case, so let's change the example below:

int main ()

{

Char buf[4];

const int a = 0;

BUF[4] = 97;

printf ("The A is%d\n", a);

}

The purpose of the last one of printf is to see if the value of variable a changes, according to the const understanding, if the const modifier is the variable can not be modified, then the value of a must not change, it must be 0. But in the results of the actual operation, we found that the value of a has become 97. This shows that the const-modified variable A has been modified by our program. That combined these two examples, let us analyze, for the second example, the reason for the modification is buf[4] assignment operation, we know BUF[4] This variable has caused the buf of this array variable cross-boundary access. BUF the member of the array itself is only 0,1,2,3, then Buf[4] who is accessing that, according to the local variable address assignment, you can know that the address of the buf[4] is the same as the address of int A, then buf[4] is actually accessing the const int A; Then the modification of buf[4] , Nature also modifies the space of the const int A, which is why we see the result of 97 when we finally print the value of a. So now we can see that the const modified variable is not allowed to modify the characteristics, then for the first example of the phenomenon of how we explain that. The first example, the error is given at the time of program compilation, note here, this time does not generate an executable file, indicating that the const modified variable can be modified by the compiler to help us protect. In the second example, the variable is modified at the time the executable executes, stating a or a variable.

In summary, we can come to the conclusion that the const modified variable, the essence is to tell the programmer or compiler that the variable is read-only, if the programmer shows in the program to modify a read-only variable, the compiler will mercilessly give an error. However, the compiler is powerless to modify the running process due to the non-canonical writing of such programs as array overflow, implicit modification, and the const modifier is still a variable attribute. 2, the const modified variables, will be protected by the operating system, to prevent changes if the first problem, there is understanding, then this problem, it is very easy to know the answer. Const-Modified variables are not protected by the operating system. The reason for this is that the operating system only protects constants, and does not protect read and write variables. So what is a constant? For example, the string "Hello World" is called a string constant. Another way to prove this problem is to look at the following procedure:

int main ()

{

const int A;

char *buf = "Hello World";

printf ("The &a is%p, the BUF is%p\n", &a, BUF);

}

It can be found that the address saved by BUF is near the address of 0x08048000, while the address of a is near the address of 0xbf000000, and the address near 0x08048000 is a code snippet on our Linux operating system. This also shows that constants and variables are stored in different areas, and the natural operating system will protect the constants. If we know the truth, then look at the following topics:

int main ()

{

char *buf = "Hello";

Buf[0] = ' a ';

printf ("The BUF is%s\n", buf);

}

We can think about what the results of this program will be?

Const usage in C language (goto)

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.