Some notes:
- the location of
const is sort of strange. const can go before or after the type; hence...
-
const int == int const
-
const int *const blah == int const *const blah
- but
const MUST come after the * to declare the pointer's address const...which makes sense given the previous rule.
-
int const* blah = int *const blah
-
int const* blah == const int *blah
Examples
- This program will compile...the offending, error generating lines are commented out.
// const int blah; // error - 'const' says 'blah' can never
// change, so we *must* initialize it.
const int blah = 0xda1e; // ok.
// blah++; // error - can't change a const-ed int.
// int* ptr = &blah; // error - without 'const' this would let
// cheat by doing like *ptr = 0xdead.
const int* ptr = &blah; // ok - ptr is a pointer to a const int.
// *ptr = 0xdead; // error - can't change contents of a
// pointer to const
int plain = 0xface;
int *ptr_plain = &plain;
// ptr_plain = ptr; // error - if this worked, you could
// cheat because you can do anything with
// 'ptr_plain'.
/// int *const ptr2 = &blah; // error - this is a const pointer -
// the address stored can't change, but
// no restrictions on changing the value
// it points to.
int *const ptr2 = &plain; // ok - this is a const pointer to int
// ptr2++; // error - can't modify a const pointer
const int *const ptr3 // ok - this is a const pointer to a
= &blah; // const int
// ptr2 = ptr; // error - can't change address ptr2
// points to
const int *ptr4 = &plain; // ok
// *ptr = 0x333; // error - the pointer can't change the
// value it points to. But you *can*
// int* const ptr3 = &blah; // change 'plain' through 'plain' itself
Puzzle (from Lippman's 'C++ Primer')
Given this:
typedef char* string
What is the effective definition of this?
const string foo
It's
not const char* foo. It's not just a macro substitution! The statement says that
string is the thing that's
const-ed.
string is a pointer to a
char. So the pointer is
const-ed, giving the answer of...
char *const foo
Note that you cannot therefore get a definition of
const char* foo out of this without doing a different
typedef as shown below. You can think of it as 'inner out' in a way.
const_int_ptr is a pointer to a constant
int and is the inner-most thing. Applying
const to this would then make this a
const pointer to
const ints.
typedef int* int_ptr;
typedef const int* const_int_ptr;
int foo = 45;
int bar = 23;
const_int_ptr pt = &foo;
// *pt = 11; // error - can't change value it points to
pt = &bar; // ok
*(pt)++; // ok
--
MattWalsh - 02 May 2005