Constants and Literals
const, constexpr, and literal types
Interview Relevant: Modern C++ practices
Constants and Literals
Constants are values that cannot be changed after initialization.
Types of Constants
- const: Runtime constant, value set once
- constexpr: Compile-time constant (C++11)
- consteval: Must be evaluated at compile time (C++20)
- #define: Preprocessor macro (avoid in modern C++)
Literal Types
- Integer: 42, 0x2A, 0b101010, 1'000'000
- Floating: 3.14, 2.5e10, 3.14f
- Character: 'A', '\n', '\x41'
- String: "Hello", R"(raw string)"
Code Examples
Using const, constexpr, and various literal types.
cpp
1// const - runtime constant
2const int MAX_SIZE = 100;
3
4// constexpr - compile-time constant
5constexpr int ARRAY_SIZE = 50;
6constexpr double PI = 3.14159265359;
7
8// constexpr function (evaluated at compile time if possible)
9constexpr int factorial(int n) {
10 return n <= 1 ? 1 : n * factorial(n - 1);
11}
12constexpr int fact5 = factorial(5); // Computed at compile time
13
14// Literal suffixes
15auto a = 42; // int
16auto b = 42L; // long
17auto c = 42LL; // long long
18auto d = 42U; // unsigned
19auto e = 3.14f; // float
20auto f = 3.14L; // long double
21
22// C++14: digit separators
23int million = 1'000'000;
24int binary = 0b1010'1010;