`const` — C++ Keyword
`const` — C++ Keyword
The const keyword in C++: marks a variable or member function as non-modifiable.
`const` — C++ Keyword
The const keyword in C++: marks a variable or member function as non-modifiable.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
constMarks an object as non-modifiable. On a member function, it guarantees the function does not modify the object's observable state.
const Type name = value; // const object
const Type& ref = expr; // const reference (read-only alias)
const Type* ptr = &obj; // pointer to const (target is read-only)
Type* const ptr = &obj; // const pointer (address is fixed)
const Type* const ptr = &obj; // both pointer and target are const
return-type func() const; // const member function
#include <print>
class Circle {
public:
explicit Circle(double r) : r_(r) {}
double area() const { // const member: cannot modify r_
return 3.14159 * r_ * r_;
}
private:
double r_;
};
int main() {
const double pi = 3.14159; // cannot be reassigned
// pi = 3.0; // error
const Circle c{5.0};
std::println("{:.4f}", c.area()); // OK: area() is const
}
const objects can only call const member functions.const& to avoid copies without allowing modification.const on a local variable enables compiler optimizations and communicates intent.constint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}