Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

What is const-correctness, and where can const be applied?

Const-correctness means marking everything that does not modify state as const, so the compiler enforces your intent. It documents the interface, prevents accidental modification, and enables optimisation.

Where it applies:

  • Variablesconst int max = 100;
  • Function parametersvoid print(const std::string& s). Passing by const& avoids a copy while promising not to modify.
  • Member functionsint size() const; promises not to modify the object, and is required for the method to be callable on a const object. Omitting it is the most common const-correctness failure.
  • Return values — returning const& to expose a member without allowing modification.
  • Pointers, in two distinct waysconst char* p is a pointer to constant data (the data cannot change), while char* const p is a constant pointer (the pointer cannot be reseated). const char* const p is both. Read these right to left.

Note: Const-correctness is viral. If a low-level function is not const-correct, every caller is forced to give up const too, which is why it must be applied from the start — retrofitting it across a large codebase is genuinely painful. Also worth knowing: mutable exempts a member from const, which is legitimate for a cache or a mutex inside a const method.

All C++ interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as