Show Lecture.Const as a slide show.
const
, when applied to a variable, means that you can’t change it.
final
variable in Java.
const
is also used to indicate an accessor member function.
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
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”
main()
,
but read-only in show_name()
.
show_name()
promises not to change it.
constexpr
, when applied to a variable, means that you can’t change it,
like const
.
constexpr auto pi = 3.14159; cout << pi << '\n';
3.14159
constexpr double avo=6.022e23; avo = 1.234; cout << avo;
c.cc:2: error: assignment of read-only variable 'avo'
Let’s try to fool constexpr
:
constexpr int answer = 42; int *p = &answer; *p = 8675309; cout << answer << '\n';
c.cc:2: error: invalid conversion from 'const int*' to 'int*'
constexpr int answer = 42; int *p = const_cast<int *>(&answer); *p = 8675309; cout << *p << ' ' << answer << '\n';
8675309 42