cpp / beginner
Snippet
Constants with const and constexpr
Constants are values that cannot change during program execution. Use const for values computed at runtime that won't change. Use constexpr for values that can be computed at compile time - these are faster because they're calculated before the program runs. Both prevent accidental modification and make code intentions clearer.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>constexpr int DAYS_IN_WEEK = 7;constexpr float PI = 3.14159f;int main() {const int MAX_PLAYERS = 4;const std::string GAME_NAME = "Chess";std::cout << GAME_NAME << " allows " << MAX_PLAYERS << " players" << std::endl;std::cout << "Pi is approximately " << PI << std::endl;std::cout << "A week has " << DAYS_IN_WEEK << " days" << std::endl;// Cannot modify: MAX_PLAYERS = 5; // ERROR!// Cannot modify: PI = 3.14; // ERROR!return 0;}
Breakdown
1
constexpr int DAYS_IN_WEEK = 7;
Compile-time constant - calculated before program runs
2
constexpr float PI = 3.14159f;
Mathematical constant calculated at compile time
3
const int MAX_PLAYERS = 4;
Runtime constant - value known only when program executes
4
const std::string GAME_NAME = "Chess";
const works with any type including std::string
5
// Cannot modify: MAX_PLAYERS = 5; // ERROR!
Attempting to modify a const variable causes a compilation error