[Original] const and pointer usage in C language, original const

Source: Internet
Author: User

[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 ~



Related Article

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.