Const keyword in C Language
Author: silent lambs
Const keyword in C language:
-- Features.
Variables that use this key modifier cannot be changed.
-- Pointer constant.
Demo:
Const char * p or char const * p
-- Constant pointer.
Demo:
Char * const p
-- Constant pointer and pointer constant.
1. Constant pointer refers to char * const p, p is a constant, and p cannot be changed.
2. pointer constants refer to char const * p. p points to a character constant, and p can be changed to point. But cannot change * p.
-- The memory of constant pointers and pointer constants is as follows.
The C ++ Programming Language provides a help note method:
Read a statement from the right to the left.
Char * const cp; (* read as pointer to) cp is a const pointer to char
Const char * p; p is a pointer to const char;
/*************************************** * *********************************> File Name: const1.c> Author: silent lambs> Mail: zshh0604@163.com> Created Time: monday ******************************** **************************************** /# include
# Include
# Define CONST_POINTER # define POINTER_CONSTint test (void) {/*** const: keyword, * variable modified using const, which cannot be modified after initialization. ** Expressions that are more likely to produce doubts after the key value is used: * 1: pointer constant * const char * p; * or * char const * p; * 2: constant pointer * char * const p; * 3: constant pointer is also the expression of pointer constant. * Const char * const * p; ** The C ++ Programming Language provides a mnemonic method: * read a declaration from The right to The left. * Char * const cp; (* read as pointer to) cp is a const pointer to char * const char * p; p is a pointer to const char; */int a = 10; int B = 20; const int * p0; // pointer constant int const * p1; // pointer constant int * const p2 = & B; // constant pointer. Const int * const p3 = & a; # ifdef CONST_POINTERp0 = & a; printf ("p0 = % d \ n", * p0); p0 = & B; printf ("p0 = % d \ n", * p0); # if 0 * p0 = 10; // p0 is a pointer to a constant character. However, p0 is not a constant. P0 points to constants of the int type. # Endifp1 = & a; printf ("p1 = % d \ n", * p1); p1 = & B; printf ("p1 = % d \ n ", * p1); # if 0 * p1 = 10; // The variable returns an error when you change the constant to which the Pointer Points. # Endif # ifdef POINTER_CONST # if 0p2 = & a; // p2 is a constant. An error occurs when you modify the p2 point to compile. # Endif * p2 = 30; printf ("p2 = % d \ n", * p2); # endif # if 0 * p3 = 10; // compilation error. P3 = & B; // compilation is incorrect. # Elseprintf ("p3 = % d \ n", * p3); # endifreturn 0;} int main (void) {test (); return 0 ;}
Reprinted please indicate the source
Http://blog.csdn.net/shaohuazuo/article/details/40316987