Difference between pointer and const qualifier const int * p and int * const p

Source: Internet
Author: User

First look at const int a = 2; the value of a is read-only.


The difference between const int * p and int * const p ,.

It can be understood as follows: divide the variable into two parts based on the "*" as the demarcation point to see who the const modifier is.

Const int * p: const modifies int, so const int is regarded as a type. Obviously, this type of memory is read-only. P pointer itself is not read-only

Int * const p: const modifies p, which is read-only like a above. The memory pointing to is not read-only and read/write.

In addition, the const int * p and int const * p statements are the same.

Example:

 

[Cpp] # include <stdio. h>
 
Static const int num = 5;
Static int a [5] = {0, 1, 2, 3, 4 };
 
Extern void print_all_address_value (const int p [], const int p1 []); // the advantage of this parameter is that data will not be changed during access ..
Extern int get_value (const int * const a); // the advantage of this parameter is that the data is not changed during access and the required data is obtained, instead of unexpected data.
Extern int set_value (int * const a, const int value); // the benefit of this parameter is that we need to change the changed data.
<PRE class = cpp name = "code">
Void main (){
Int * p, * p1;
P =;
P1 = & a [0];
Print_all_address_value (p, p1 );
Set_value (p + 1, 9 );
Get_value (p1 + 1 );
Printf ("value p1 = % d \ n", get_value (p + 1 ));
}
 
Extern void print_all_address_value (const int p [], const int p1 []) {
Int I = 0;
For (I = 0; I <num; I ++ ){
Printf ("for address a = % p, p = % p, p1 = % p \ n", & a [I], p, p1 );
Printf ("for value a = % d, p = % d, p1 = % d \ n", a [I], * p, * p1 );
P ++;
P1 ++;
}
}
 
Extern int get_value (const int * const ){
Return *;
}
Extern int set_value (int * const a, const int value ){
* A = value;
Return *;
}
</PRE>
<P> </P>
<PRE> </PRE>

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.