- 2070 Chaitra · 2 marks
Task of const keyword
Short answer
The const keyword declares an entity as read-only after initialization, preventing modification. It applies to variables, pointers, function arguments, member functions, and objects, ensuring compile-time safety against unintended changes.
What is the task of const keyword?
The const keyword declares that a value cannot be modified after initialisation. Any attempt to change it gives a compile-time error.
Uses:
- Constant variable - replaces
#defineand is type safe:const float PI = 3.14159; - Pointer to constant - the data cannot change through the pointer:
const int *p; - Constant pointer - the pointer cannot point elsewhere:
int *const p = &x; - Constant function argument - protects the argument:
void show(const int &x); - Constant member function - promises not to change the object's data:
int getX() const { return x; } - Constant object - can call only const member functions.
const int MAX = 100;
// MAX = 200; // error: assignment of read-only variable
✓ Answer checked by Claude Opus 5.5 (high effort)