分类: C/C++
2011-03-30 22:31:30
CONSTANT KEYWORD
char *p
= "Hello" // non-const pointer, non-const data |
I have
this explanation I wrote a long time ago stored away in a file, so to
elaborate:
This
file explains how const works.
The
following declarations are identical:
const char* p; |
Both
declare a pointer to a constant character. The second is slightly
better
in the sense that the declaration can be read from right-to-left:
"p
is a pointer to a const char". Read as such, it is easy to see that
the line
*p = 'c'; will not compile.
The
following declaration:
char* const p; |
declares
p to be a constant pointer to a character. That is:
p = "foo"; // Does not
compile |
And
thus:
const char* const p; |
both
declare p to be a constant pointer to a constant character, and
so none
of the following lines of code compile:
p = "foo"; |
Now
throw another pointer into the mix:
const char** p; |
These
are equivalent and declare p to be a pointer to a pointer to a
constant
character. That is:
p = ptr-to-ptr-to-char; // Compiles |
Or how
about creative placement of const:
char* const* p; |
This
declares p to be a pointer to a constant pointer to a character.
That is:
p = ptr-to-constptr-to-char; //
Compiles |
And the ever-popular:
char** const p; |
Which
declares p to be a constant pointer to a pointer to a character.
Or:
p = ptr-to-ptr-to-char; // Does not
compile |
And now
we get just plain const happy:
const char* const* p; |
p is a
pointer to a constant pointer to a constant character. The only
thing
you can do with this one (besides remove the code and rewrite) is:
p =
ptr-to-constptr-to-constchar;
const char** const p; |
p is a
constant pointer to a pointer to a constant character. The only
thing
you can do with this is:
*p =
ptr-to-constchar;
And this
beast:
const char* const* const p; |
Well, it
won't pass code review since nobody will understand it, but at
any
rate... We've achieved maximum constant-ness with this line. You
can't do
anything at all with p, what it points to, what that points to,
or what
"what that" points to. You can print it. That's about it.