cpp / beginner
Snippet
Const and constexpr: Defining Immutability
const defines a value that cannot be changed after initialization, useful for configuration values. constexpr defines values that are computed at compile time, enabling faster execution. Both prevent accidental modification of important values.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>using namespace std;const int MAX_SCORE = 100;constexpr int DOUBLE(int x) { return x * 2; }int main() {int playerScore = 75;if (playerScore > MAX_SCORE) {cout << "Invalid score" << endl;}cout << "Double: " << DOUBLE(5) << endl;return 0;}
Breakdown
1
const int MAX_SCORE = 100;
A constant that cannot be modified after creation
2
constexpr int DOUBLE(int x) { return x * 2; }
A compile-time constant function