By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,655 Members | 964 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,655 IT Pros & Developers. It's quick & easy.

why does this right?

P: n/a
when i read msdn, i find this code below. it confused me.

const char cch = 'A';
char ch = 'B';

const char *pch1 = &cch;
const char *const pch4 = &cch;
const char *pch5 = &ch; // why does this correct?
char *pch6 = &ch;
char *const pch7 = &ch;
const char *const pch8 = &ch;

i write test. find that you can change the /ch/ value, but can not
change the /*pch5/ value.
why ?

anyone can help me?
thanks!

Nov 1 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
depp wrote:
when i read msdn, i find this code below. it confused me.

const char cch = 'A';
char ch = 'B';

const char *pch1 = &cch;
const char *const pch4 = &cch;
const char *pch5 = &ch; // why does this correct?
You declare a pointer to a const char and assign the address of
a non-const char to it. That means that 'ch' cannot be changed
*though* this pointer.
char *pch6 = &ch;
char *const pch7 = &ch;
const char *const pch8 = &ch;

i write test. find that you can change the /ch/ value, but can not
change the /*pch5/ value.
why ?
pch5 is a pointer to a const char (at least that's how it's declared).
So, *pch5 is a const char. You cannot change a const object. It does
not matter that pch5 and &ch represent the same location in memory.
They represent it differently. 'ch' is mutable (changeable), *pch5 is
not.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 1 '06 #2

P: n/a

Victor Bazarov wrote in message ...
>depp wrote:
>when i read msdn, i find this code below. it confused me.

const char cch = 'A';
char ch = 'B';

const char *pch1 = &cch;
const char *const pch4 = &cch;
const char *pch5 = &ch; // why does this correct?

You declare a pointer to a const char and assign the address of
a non-const char to it. That means that 'ch' cannot be changed
*though* this pointer.
>char *pch6 = &ch;
char *const pch7 = &ch;
const char *const pch8 = &ch;

i write test. find that you can change the /ch/ value, but can not
change the /*pch5/ value.
why ?

pch5 is a pointer to a const char (at least that's how it's declared).
So, *pch5 is a const char. You cannot change a const object. It does
not matter that pch5 and &ch represent the same location in memory.
They represent it differently. 'ch' is mutable (changeable), *pch5 is
not.
V
Here we go again! Remember last year? <G>

OP see:

Alf P. Steinbach's "Pointers" document:
http://home.no.net/dubjai/win32cpptu...ters/ch_01.pdf

--
Bob R
POVrookie
Nov 1 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.