Constants and literals
5.1 — Constant Variables (Named Constants)¶
A constant variable is a variable whose value cannot be changed once it has been initialized.
-
The
constkeyword: Placingconstbefore or after the data type makes the variable a constant (e.g.,const int gravity { 9 };). -
Initialization: Constant variables must be initialized when they are defined.
-
Why use them? They prevent "magic numbers" (unexplained literals) and ensure that values that shouldn't change (like \(\pi\)) aren't accidentally modified.
5.2 — Literals¶
Literals are values inserted directly into the source code.
-
Suffixes: You can use suffixes to tell the compiler the specific type of a literal:
-
5(int) vs5L(long) vs5u(unsigned int). -
5.0(double) vs5.0f(float).
-
-
String Literals: Encased in double quotes (e.g.,
"Hello"). Unlike character literals ('a'), string literals can contain multiple characters and end with a hidden null terminator (\0).
5.3 — Numeral Systems¶
C++ allows you to represent integers in different bases:
-
Decimal: The default (Base 10).
-
Binary: Prefixed with
0b(e.g.,0b1010is 10). -
Hexadecimal: Prefixed with
0x(e.g.,0xFis 15). Common in memory addresses and color codes. -
Octal: Prefixed with
0(e.g.,012is 10). Caution: Leading zeros can cause accidental octal conversion.
5.4 — The As-If Rule and Compile-Time Optimization¶
-
The As-If Rule: The compiler is allowed to modify your code to make it faster as long as the "observable behavior" remains the same.
-
Constant Folding: If you write
int x = 3 + 4;, the compiler will likely replace it withint x = 7;during compilation so the math isn't done at runtime.
5.5 & 5.6 — Constant Expressions and Constexpr¶
This is a critical distinction in modern C++.
-
Constant Expression: An expression that can be fully evaluated at compile-time (e.g.,
3 + 4). -
const: Means the value cannot change after initialization. It might be initialized at runtime (e.g., from user input). -
constexpr: Short for "constant expression." It guarantees the variable is a compile-time constant. If the value cannot be determined at compile-time, the compiler will throw an error.- Rule of Thumb: Use
constexprfor any constant that can be determined at compile-time. Useconstfor values that are determined at runtime but don't change once set.
- Rule of Thumb: Use
5.7 — Introduction to std::string¶
The std::string class (from the <string> header) handles sequences of characters.
-
Input with
std::cin: Only reads up to the first whitespace (space, tab, newline). -
Input with
std::getline(): Used to read a full line of text, including spaces.- Usage:
std::getline(std::cin >> std::ws, myString);(Thestd::wsignores leading whitespace/newlines from previous inputs).
- Usage:
-
Performance:
std::stringis "expensive" because it often makes a copy of the text in memory.
5.8 & 5.9 — Introduction to std::string_view¶
Introduced in C++17, std::string_view (from the <string_view> header) provides a read-only view of a string that already exists elsewhere.
-
Efficiency: It does not make a copy of the string. It only stores a pointer to the start of the string and a length.
-
When to use: Use
std::string_viewfor function parameters when the function only needs to read the string. This makes your code much faster. -
The Danger: A
string_viewdoes not "own" the string. If the original string is destroyed, thestring_viewbecomes "dangling" (pointing to invalid memory), leading to undefined behavior.
Summary Table: const vs constexpr vs string_view¶
| Feature | const | constexpr | std::string_view |
|---|---|---|---|
| Primary Goal | Prevent modification | Force compile-time evaluation | Efficient read-only string access |
| When Initialized | Runtime or Compile-time | Only Compile-time | Runtime (points to existing data) |
| Memory Cost | Same as standard variable | Often zero (replaced by value) | Very low (pointer + length) |
| Ownership | Owns its value | Owns its value | Does not own the data |