What is the usage of const in C++?

In C++, the const keyword is used to declare constants. It can be used on variables, function parameters, and function return types as follows:

  1. Declare constant variables: use the keyword “const” to denote that the value of the variable cannot be changed. For example:
const int num = 10;
  1. Function parameters: using the const modifier on a function’s parameters indicates that the parameter’s value cannot be changed within the function. This ensures that the function will not inadvertently modify the parameter and cause errors. For example:
void printString(const std::string& str) {
    // 无法修改str的值
    std::cout << str << std::endl;
}
  1. Function return type: Using ‘const’ to modify the return type of a function indicates that the return value of the function is a constant and cannot be modified. For example:
const int getValue() {
    return 10;
}

When using this type of function, the return value cannot be modified, for example:

int num = getValue(); // 正确
num = 20; // 错误,无法修改常量

In summary, the ‘const’ keyword can be used to declare constant variables, function parameters, and function return types to restrict unchangeable values, thereby enhancing the robustness and readability of the program.

bannerAds