Topic 6 of 83
Variables & Constants
Overview
Variables are named memory locations used to store data. Constants are variables whose values cannot be changed after initialization, ensuring safety and enabling compiler optimizations.
Syntax
cpp
int score = 10; // Regular variable
const double PI = 3.14159; // Runtime/Compile-time constant
// constexpr strictly requires compile-time evaluation
constexpr int MAX_USERS = 100 * 5;Common Pitfalls
- Failing to initialize a const variable at the time of declaration. (e.g., `const int x; x = 5;` is illegal).
- Using uninitialized regular variables, which will contain garbage values.
Interview Tips
- Explain the difference between const (can be evaluated at runtime) and constexpr (must be evaluated at compile-time).
- Using const aggressively ('const correctness') is a highly valued practice in professional C++ development.
Real-World Example
Using constants to avoid 'magic numbers' in code.
example
cpp
#include <iostream>
using namespace std;
int main() {
const double TAX_RATE = 0.08;
double price = 50.0;
double finalPrice = price + (price * TAX_RATE);
cout << "Total: $" << finalPrice << "\n";
return 0;
}