![]() |
CMPT 212
Spring 1998
|
const float pi = 3.0; pi = 3.14159; // causes a compiling error.
void f(const int x) { x = 7; // error. } void g(const bigStruct& w) { w = ...; // error. }In function g, w is passed by reference for efficiency, but is defined with const to guarantee that w will not be changed in g.
int x = 8; int * y; y = &x; cout << x; // outputs 8. cout << y; // outputs 11. cout << &x; // outputs 11. cout << &y; // outputs 14. cout << &(&x); // error: &x has no address. cout << &(&y); // error: &y has no address.
int * y; // y is a pointer to an int.
int w;
w = *y; // *y is the int that y points to.
int x;
int * y;
y = &x;
*y = 3; // x also becomes 3.
cout << x; // outputs 3.
x = 4;
cout << (*y); // outputs 4.
int x = 3; int w = 4; const int * y; // y is a pointer to a "const int". y = &x; *y = 7; // error: y is pointing to a constant, and // we cannot change a constant. y = &w; w = 5;
int x = 3; int w = 4; int * const y = &x; // constants must be initialized. *y = 5; x = 6; y = &w; // error: y is a constant, and we // cannot change a constant.
int x = 3; int w = 4; const int * const y = &x; // constants must be initialized. x = 5; *y = 6; // error: y is pointing to a constant. y = &w; // error: y is a constant. w = 7;
const int * p;
int * const p = ...;
const int * const p = ...;
![]() Return to lecture notes index |
|
This page is maintained by simpson@cs.sfu.ca. | Last updated on 21 Jan 1998. |