|
int a ; read as: a is an int
int const a ; read as: const a is an int
<==> a is an int and you cannot update a
|
int const *p ;
|
Answer:
int const *p means:
const *p is an int
<==> *p is an int and you cannot update *p
<==> p is a reference to an int
and you cannot update *p
|
|
Example:
int main(int argc, char *argv[])
{
int a;
int const *p; // You CANNOT update *p !
a = 4;
p = &a;
*p = 100; // Illegal !!!
}
|
Result:
UNIX>> gcc const1.c const1.c: In function 'main': const1.c:15: error: assignment of read-only location '*p' |
How to run the program:
|
int * const q ;
|
Answer:
int * const q means:
* const q is an int
<==> const q is a reference variable to an int
<==> q is a reference variable to an int
and you cannot update q
|
|
Example:
int main(int argc, char *argv[])
{
int a = 4;
int b = 7;
int * const q = &a; // q points to a, and you cannot update q
printf ("a = %d, b = %d\n", a, b);
*q = 555; // You CAN update *q (it is not the same as p)
printf ("a = %d, b = %d\n", a, b);
q = &b; // Illegal - can't update q !!!
/* --------------------------
Contrast with this:
-------------------------- */
int const * p = &a; // *p is a const
p = &b; // You CAN update p
*p = 555; // Illegal: You CANNOT update *p
}
|
Result:
UNIX>> gcc const2.c const2.c: In function 'main': const2.c:line 20: error: assignment of read-only variable 'q' const2.c:line 31: error: assignment of read-only location '*p' |
How to run the program:
|
Exercise:
|