How to use the const qualifier in C++?

In C++, the const qualifier is used to modify variables, function parameters, and function return values. It informs the compiler that the item is constant and cannot be changed.

  1. Modify variables.
const int num = 10; // 常量num的值不能被修改
  1. Modify function parameters.
void func(const int num) {
    // 函数体
}

In this example, the parameter num of the function func is declared as a constant, and its value cannot be changed within the function body.

  1. Modifying the function return value:
const int func() {
    // 函数体
    return 10;
}

In this example, the returned value of the function “func” is declared as a constant, indicating that the value cannot be modified.

It is important to note that the const qualifier must come before the type name and constants must be initialized at the declaration. Additionally, when const is used to modify an object, it ensures that the object’s initial value cannot be changed. Furthermore, the const qualifier can also be used with reference types to declare a reference that cannot be modified.

bannerAds