cpp / beginner
Snippet
const and constexpr for Constants
const marks values that cannot change after initialization, useful for function parameters and local variables. constexpr requests compile-time evaluation, meaning the compiler calculates the value before the program runs. Using constants makes code clearer and prevents accidental modifications.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>const int MAX_SCORE = 100;constexpr int ARRAY_SIZE = 5;int getMultiplier(int level) {const int baseMultiplier = 2;return baseMultiplier * level;}constexpr int square(int x) {return x * x;}int main() {const float PI = 3.14159f;std::cout << "Max score: " << MAX_SCORE << std::endl;std::cout << "PI: " << PI << std::endl;std::cout << "Square of 7: " << square(7) << std::endl;std::cout << "Multiplier at level 3: " << getMultiplier(3) << std::endl;int numbers[ARRAY_SIZE] = {1, 2, 3, 4, 5};for (int i = 0; i < ARRAY_SIZE; i++) {std::cout << numbers[i] << " ";}std::cout << std::endl;return 0;}
Breakdown
1
const int MAX_SCORE = 100;
A constant variable that can never be changed after it's set, the compiler will flag any attempt to modify it
2
constexpr int ARRAY_SIZE = 5;
A compile-time constant the compiler evaluates before the program runs, enabling use in array declarations
3
const int baseMultiplier = 2;
A const variable inside a function that won't change, clarifying intent in your code
4
constexpr int square(int x)
A function that must evaluate at compile-time when given constant arguments, enabling compile-time calculation
5
int numbers[ARRAY_SIZE]
Uses the constexpr ARRAY_SIZE to create an array with a fixed, compile-time determined size