⚙️ C++ Beginner

What is the const keyword in C++?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid C++ basics — a prerequisite for any developer role.

Answer

The const keyword declares that a value cannot be modified after initialization, enabling compiler-enforced immutability and enabling optimizations. Const variables: const int MAX_SIZE = 100; // Must be initialized MAX_SIZE = 200; // ERROR!. Const pointers (four combinations): const int* p1 = &x; // Pointer to const int -- can't change *p1 int* const p2 = &x; // Const pointer to int -- can't change p2 const int* const p3 = &x; // Const pointer to const -- can't change either int* p4 = &x; // Neither const -- can change both. Memory aid: read right to left: "p3 is a const pointer to const int." Const function parameters: void printName(const std::string& name) { // name is read-only std::cout << name; }. Pass by const reference: efficient (no copy) + safe (can't modify). Const member functions: a function that doesn't modify object state — can be called on const objects: class Car { std::string brand; public: std::string getBrand() const { return brand; } // Const function void setBrand(std::string b) { brand = b; } // Non-const }; const Car c("Toyota"); c.getBrand(); // OK -- const function c.setBrand("Honda"); // ERROR -- non-const on const object. mutable: a member declared mutable can be modified even in const functions (for caching/lazy initialization): mutable int cacheCount = 0;. constexpr (C++11): evaluated at compile time: constexpr int square(int x) { return x*x; } constexpr int val = square(5); // 25 at compile time.

Pro Tip

This topic has C++-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.