Mastering const vs constexpr in C++: Key Differences and Interview Tips
This article explains the distinct roles of const and constexpr in C++, covering their usage with variables, pointers, function parameters, and class members, comparing compile‑time and run‑time behaviors, and offering practical interview strategies and code examples for developers.
Part 1 – const: The Guardian of Read‑Only
Before diving into constexpr, we review the basic usage of const. It modifies variables, pointers, function parameters, and member functions to indicate a read‑only property, meaning the value cannot be changed after initialization.
1.1 Modifying variables: making values immutable
When const decorates a regular variable, the variable becomes a constant whose value cannot be altered after initialization.
const int num = 10;
num = 20; // compile error, cannot modify a const valueThis is useful for defining fixed values such as mathematical constants or configuration parameters.
const double PI = 3.1415926;
double radius = 5.0;
double area = PI * radius * radius;1.2 Modifying pointers: multi‑dimensional restrictions
Depending on the position of const, pointers can be categorized as:
(1) Pointer to const : const int* ptr points to a constant value; the pointer itself can change.
int value = 10;
const int* ptr = &value;
// *ptr = 20; // error
ptr = &value; // OK(2) Const pointer : int* const ptr makes the pointer itself immutable; the pointed value can change.
int value1 = 10;
int* const ptr = &value1;
*ptr = 30; // OK
// ptr = &value2; // error(3) Const pointer to const : const int* const ptr cannot modify either the pointed value or the pointer.
int value = 10;
const int* const ptr = &value;
// *ptr = 20; // error
// ptr = &value; // error1.3 Modifying function parameters: ensuring parameter safety
When const decorates a function parameter, the function cannot modify the argument, improving safety and readability.
void printValue(const int value) {
// value = 20; // compile error
std::cout << value << std::endl;
}Calling printValue(num) leaves num unchanged.
1.4 Modifying member functions: preserving class state
Appending const to a member function declares it a constant member function, guaranteeing it does not modify non‑static members.
class MyClass {
private:
int value;
public:
MyClass(int v) : value(v) {}
int getValue() const {
// value = 20; // error
return value;
}
};
const MyClass obj(10);
int val = obj.getValue();Part 2 – constexpr: The Creator of Compile‑Time Constants
constexpr, introduced in C++11, declares constant expressions whose values are known at compile time, applying to both variables and functions.
2.1 Modifying variables: compile‑time determined values
Variables marked constexpr must have values determinable during compilation.
constexpr int num = 10;
constexpr int result = num + 5; // result is 15 at compile timeUnlike const, which can be initialized with run‑time values, constexpr requires a constant expression.
int value = 10;
const int num = value; // OK, run‑time const
// constexpr int num1 = value; // errorconstexpr is especially useful for array sizes:
constexpr int size = 10;
int arr[size]; // array size known at compile time2.2 Modifying functions: compile‑time evaluation
constexpr can also decorate functions, making them constant‑expression functions that are evaluated at compile time when called with compile‑time arguments.
constexpr int square(int x) {
return x * x;
}
constexpr int result = square(5); // result = 25 at compile timeIf the argument is not a compile‑time constant, evaluation occurs at run time.
int a = 5;
int result1 = square(a); // run‑time evaluationC++14 relaxes restrictions, allowing loops and local variables:
constexpr int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
constexpr int res = factorial(5); // res = 120 at compile time2.3 constexpr in classes: compile‑time object creation
Constructors and member functions can be constexpr, enabling compile‑time creation of objects.
class Point {
public:
constexpr Point(double xVal, double yVal) : x(xVal), y(yVal) {}
constexpr double getX() const { return x; }
constexpr double getY() const { return y; }
private:
double x, y;
};
constexpr Point origin(0, 0); // compile‑time objectPart 3 – Comprehensive Comparison of const and constexpr
Having explored each keyword, we now compare them across several dimensions.
3.1 Constant nature: run‑time vs compile‑time
const values can be determined at run time, suitable for configuration parameters or user input.
int getConfigValue();
const int configNum = getConfigValue();constexpr values must be known at compile time, useful for array sizes and template arguments.
constexpr int num = 10;
int arr[num];3.2 Scope of application: breadth vs specialization
const applies to variables, pointers, function parameters, and member functions, offering wide flexibility.
// variable
const int value = 10;
// pointer variations
int num = 20;
const int* ptr1 = # // pointer to const
int* const ptr2 = # // const pointer
const int* const ptr3 = # // const pointer to const
// function parameter
void func(const int param) {}
// member function
class MyClass { int data; public: int getData() const { return data; } };constexpr mainly targets variables and functions (including class constructors) where compile‑time evaluation is required.
constexpr int result = 5 + 3;
constexpr int multiply(int a, int b) { return a * b; }
constexpr int product = multiply(4, 6);
class Point { public: constexpr Point(double x, double y) : x(x), y(y) {} constexpr double getX() const { return x; } constexpr double getY() const { return y; } private: double x, y; };
constexpr Point origin(0, 0);3.3 Function decoration: evaluation timing and requirements
const on a function merely indicates the return value is immutable; the function runs at run time.
const int calculate() {
int a = 5;
int b = 3;
return a + b; // run‑time calculation
}constexpr functions must be evaluable at compile time when called with constant arguments, with stricter body requirements (C++11: single return; C++14: more complex but still compile‑time).
// C++11 style
constexpr int add(int a, int b) { return a + b; }
// C++14 style
constexpr int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; ++i) result *= i;
return result;
}Part 4 – Interview Strategies Summary
Reflecting on the interview where const and constexpr stumped me, I realized the importance of clear, accurate answers. Below are practical tips for handling such questions.
Explain concepts concisely : State that const enforces read‑only semantics for variables, pointers, parameters, and member functions, while constexpr declares constant expressions evaluated at compile time.
Compare differences explicitly : Highlight run‑time vs compile‑time determination, breadth of applicability, and function evaluation constraints.
Use code examples : Show pointer variations with const, simple constexpr variable and function examples, and class constexpr constructors to demonstrate practical usage.
Prepare thoroughly : Review C++ fundamentals, practice writing const and constexpr code, and relate them to real project scenarios.
Stay confident : Present the differences methodically, and back up explanations with short, correct snippets.
By studying these insights, you can approach future C++ interviews with confidence and increase your chances of securing the desired offer.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Deepin Linux
Research areas: Windows & Linux platforms, C/C++ backend development, embedded systems and Linux kernel, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
