Mail Archives: djgpp/1998/04/29/12:32:37
Jakub wrote:
> Could someone help me out here.
>
> example:
>
> const char *name1 = "John"; // Value cannot be changed
>
> Is the above the same as?:
> const char something = "John";
> char *name1;
> name1 = &something;
>
> What would be the expansion of the following?
> char *const name2 = "John"; // Pointer cannot be changed
Here and the different meanings of the const keyword:
const int ki = 0; // means "constant int"
ki = 2; // illegal
const int aki[3] = { 1, 2, 3 }; // means "constant array of int"
aki = ...; // illegal in any case; array name is not an lvalue
aki[0] = 0; // illegal; array is const
const int *pki = &ki; // means "pointer to constant int"
pki = &aki[0]; // legal; pointer can be changed
*pki = 0; // illegal; pointer is to constant int
int *const kpi = &ki; // means "constant pointer to int"
pki = &aki[0]; // illegal; pointer is const
*pki = 0; // legal; pointer is const, but not the int it points to
const int *const kpki = &ki; // means "constant pointer to
// constant int"
kpki = &aki[0]; // illegal; pointer is const
*kpki = 0; // also illegal; pointed-to int is also const
So in summary: a const near the pointed-to type means that the value
pointed to, or the values in the array, cannot be changed. In the case
of pointers, a const after the * means that the point itself is const,
which is independent of whether the point-to type is.
Remember to always read C declarations inside-out. For instance:
(const int (*(const (kpki))))
means kpki is a const pointer to const int.
--
Erik Max Francis, &tSftDotIotE / mailto:max AT alcyone DOT com
Alcyone Systems / http://www.alcyone.com/max/
San Jose, California, United States / icbm:+37.20.07/-121.53.38
\
"Heaven and hell / is on Earth"
/ Salt-n-Pepa
- Raw text -