[Original] const and pointer usage in C language, original const
I have been preparing for the written examination recently to make up for my class in arrears. I encountered this question when I reviewed the C language:
12345 |
int a= 248 , b= 4 ; int const c= 21 ; const int *d=&a; int * const e=&b; int const * const f =&a; |
Which of the following expressions will be forbidden by the compiler?
A:*c=32
B:*d=43
C: e = &
D: f = 0x321f
E: d = & B
F: * e = 34
The following are analyzed one by one
The first line of code is not mentioned. The second line,int
const
c=
21
; And const int c = 21; indicates that c is modified to const, that is, the value of c cannot be changed. So A must be wrong. c is not A pointer;
Row 3:const
int
* D = & a; indicates that the value pointed to by d cannot be changed through the pointer, So B: * d = 43 is incorrect. The direction of d is variable. HERE d = & a, E: d = & B is also correct;
Row 4:int
*
const
E = & B; indicates that the point of pointer e cannot be changed, so C is wrong. However, the point value can be changed. * e = 34 is correct, and F is correct;
Fifth line:int
const
*
const
F = & a; indicates that neither the pointing or pointing content of pointer f can be changed. D is incorrect.
The answer is ABCD.
Here, Baidu encyclopedia introduces a method:
If the const is on the left side of *, the value of the variable pointed to by the pointer cannot be changed directly through the pointer (it can be changed through other means); if the value is on the right side of *, the pointer cannot be changed. Note: "Left value, right direction"
However, be sure to note that int * const p; int const * const p; or const int * const p; the Pointer Points cannot be changed and an address must be initialized during definition.
Basically, const is okay ~