Junior — Middle
What is the role and purpose of the 'const' keyword in programming languages?
sobes.tech AI
Answer from AI
The keyword const in C/C++ is used to declare constant values or pointers that cannot be changed after initialization. It helps improve code safety by preventing accidental data modification.
Main uses:
- Declaring constant variables:
const int maxValue = 100; - Declaring pointers to constants (data cannot be changed through the pointer):
const int* ptr = &maxValue; // cannot change *ptr - Declaring constant pointers (the address cannot be changed):
int* const ptr = &someVar; // cannot change ptr - Using in function parameters to protect passed data from modification:
void printValue(const int& value) { // value cannot be modified inside the function std::cout << value; }
Thus, const serves to document intentions and prevent errors related to data modification.