1). The function of the keyword const is to convey very useful information to the person who is reading your code, and in fact, declaring a parameter as a constant is to tell the user the purpose of the application of this parameter. If you have spent a lot of time cleaning up the rubbish left by others, you will soon learn to thank for the extra information. (Of course, it's very rare for a const programmer to leave rubbish for others to clean up.) ) 2). Using the keyword const may produce more compact code by giving the optimizer some additional information. 3). The use of the keyword const can make it natural for the compiler to protect those parameters that you do not want to change, and to prevent them from being unintentionally modified by the code. In short, this can reduce the occurrence of bugs. |
#include <stdio.h> void Main (void) { int const A = 10; int *p = (int*) &a; *p = 20; printf ("&a=%d\n", &a); printf ("p=%d\n", p); printf ("a=%d\n", a); printf ("*p=%d\n", *p); } &a=-1081948900 p=-1081948900 A=20 *p=20 |
|
1) Modifier general constants general constants refer to constants of simple types const int A; int const A; 2) modifier constant pointer const int *A, int co NST *a; The const modifier points to the object, a variable, the object that a points to is not mutable int *const A; Const modifier pointer A, a immutable, variable a pointing to an object const int *const A; Pointers A and a object are not mutable 3) The constant-parameter const modifier of the modifier function can also modify the function's pass-through parameters, in the following format: void fun (const int Var); Tells the compiler that Var cannot be changed in the body of the function, thus preventing some unintentional or erroneous modifications by the user. |
#include <stdio.h> int const A = 10; void Main (void) { int *p = (int*) &a; *p = 20; printf ("%d\n", *p); } Segment Error |
#include <stdio.h> void Main (void) { int const A = 10; int B = 20; int *p = (int*) &a; *p = 20; printf ("&a=%x\n", &a); printf ("&b=%x\n", &b); printf ("p=%x\n", p); printf ("a=%d\n", a); printf ("*p=%d\n", *p); } &a=bfbc9c1c &b=bfbc9c18 P=bfbc9c1c A=20 *p=20 From this you can see that the value of a is present in the stack. |