Question about declaring const pointer to const value

L

linq936

Hi,
I have the following code:

int main(){ /* line 1 */
const int i = 10; /* line 2 */
const int j = 20; /* line 3 */
/* line 4 */
int const * const p = &i; /* line 5 */
const int * const p2 = &j; /* line 6 */
/* line 7 */
(*p2)++; /* line 8 */
(*p)++; /* line 9 */

return 0;
}

Compiler does not complain line 6 and errors out on those
incremental statements of line 8 and 9.

So the declaration on line 5 and line 6 are the same? I mean "int
const * const" and "const int * const" are same?

It is a little hard to grasp how to use "const" in declaration.

Any tip?
 
C

CBFalconer

linq936 said:
I have the following code:

int main(){ /* line 1 */
const int i = 10; /* line 2 */
const int j = 20; /* line 3 */
/* line 4 */
int const * const p = &i; /* line 5 */
const int * const p2 = &j; /* line 6 */
/* line 7 */
(*p2)++; /* line 8 */
(*p)++; /* line 9 */

return 0;
}

Compiler does not complain line 6 and errors out on those
incremental statements of line 8 and 9.

So the declaration on line 5 and line 6 are the same? I mean "int
const * const" and "const int * const" are same?

It is a little hard to grasp how to use "const" in declaration.

The thing that counts is which side of the * the 'const' is.
"const int *p" means p is a non-constant pointer which points at
read-only int(s). "int * const p = &x;" means p is a read-only
pointer, set to point at the variable x, and which can only be set
at this declaration point.

Try to use fixed width fonts, so as to avoid the silly widths.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top