Sobes.tech
Junior — Middle

Can you explain the purpose and use of the keyword 'const' in programming language?

sobes.tech AI

Answer from AI

The keyword const in C/C++ is used to declare constant values or to indicate that data should not be modified after initialization. This helps improve code safety and prevents accidental changes to variables.

Examples of usage:

  • Constant variable:
const int maxValue = 100; // maxValue cannot be changed
  • Constant pointer to data:
const int* ptr; // cannot change data through ptr
  • Pointer to constant data:
int* const ptr; // cannot change the address that ptr points to
  • Constant class method:
class MyClass {
public:
    int getValue() const { return value; } // method does not modify the object state
private:
    int value;
};

Using const helps the compiler detect errors and improves code readability by showing the developer's intentions.