const against non const pointer

M

mathon

Hello,

if i have these two declarations:

1)const int * test;

and

2)int* const test;


Does the first mean that the value of the integer cannot be changed and
the second one that the location to which the pointer points to cannot
be changed...? or is the other way around?

matti
 
N

Noah Roberts

Hello,

if i have these two declarations:

1)const int * test;

and

2)int* const test;


Does the first mean that the value of the integer cannot be changed and
the second one that the location to which the pointer points to cannot
be changed...? or is the other way around?

You have it right.
 
A

Andrey Tarasevich

if i have these two declarations:

1)const int * test;

and

2)int* const test;


Does the first mean that the value of the integer cannot be changed and
the second one that the location to which the pointer points to cannot
be changed...? or is the other way around?

The first variant means that the integer the pointer points to cannot be changed
through pointer 'test' without an explicit cast. Note that it is still possible
that the integer can be changed through some other access path (directly or
through some other pointer). Also note that if the integer itself is not a
constant object, it is perfectly legal to cast away the constness an change it
through 'test':

*const_cast<int*>(test) = 42;

The second variant means that pointer 'test' cannot be changed (as I understand,
that what you meant by "the location to which the pointer points to cannot be
changed").
 
M

Mark P

Hello,

if i have these two declarations:

1)const int * test;

and

2)int* const test;


Does the first mean that the value of the integer cannot be changed and
the second one that the location to which the pointer points to cannot
be changed...? or is the other way around?

matti

Others have already confirmed that you are correct. As a tip, these
sorts of declarations, notably ones with brackets or parentheses, can in
general be read right to left:

1) test is a pointer to an int constant
2) test is a constant pointer to an int

For more complicated declarations, check out:

http://www.ericgiguere.com/articles/reading-c-declarations.html
(it's a bit old and written for C, but the basic ideas still hold)

Finally, there's a handy little UNIX utility that will convert
declarations to english and vice versa. Look for cdecl or c++decl.
 

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

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top