See this page as a slide show
CS253 Const
const
const
, when applied to a variable, means that you can’t change it.
- It’s like a
final
variable in Java.
- It does not mean that the memory is read-only;
it just means that you can’t write it.
- A given piece of memory may be read-only to one part of a program,
but read-write to another.
const
is also used to indicate an accessor member function.
Example
const int BOARD_SIZE = 8;
char chessboard[BOARD_SIZE][BOARD_SIZE];
for (int i=0; i<BOARD_SIZE; i++)
for (int j=0; j<BOARD_SIZE; j++)
chessboard[i][j] = ' ';
if (chessboard[3][2] == ' ') // Empty position?
chessboard[3][2] = 'R'; // put a rook there
cout << chessboard[3][2] << '\n';
R
Reference example
void show_name(const string &name) {
cout << "The name is: “" << name << "”\n";
}
int main(int, char *argv[]) {
string s = argv[0];
show_name(s);
}
The name is: “./a.out”
- The string is read-write in
main()
,
but read-only in show_name()
.
- The string memory itself is read-write. It’s just that
show_name()
promises not to change it.