乐闻世界logo
搜索文章和话题

How many and which are the uses of " const " in C++?

1个答案

1

In C++, the 'const' keyword is a fundamental element used to define constants, whose values remain immutable at runtime. Specifically, 'const' in C++ has several primary uses:

  1. Defining Constant Variables: The 'const' keyword can be used to define a constant variable, guaranteeing that its value remains immutable after initialization. For example:

    cpp
    const int MAX_AGE = 100;

    In this example, MAX_AGE is defined as a constant with a value of 100, which cannot be modified later in the program.

  2. Combining 'const' with Pointers: The 'const' keyword can be combined with pointers to define pointers to constants or constant pointers.

    • Pointer to const: This indicates that the data pointed to by the pointer cannot be modified via this pointer, even though the pointer itself can be changed to reference other addresses.

      cpp
      const int* ptr = &MAX_AGE;
    • Const pointer: This means the pointer's value (i.e., the address it stores) cannot be changed, but the data it points to can be modified.

      cpp
      int age = 30; int* const ptr = &age; *ptr = 31; // Allowed // ptr = &MAX_AGE; // Error, ptr is a const pointer
  3. 'const' in Functions: In function declarations, 'const' can be used to qualify function parameters, ensuring that the parameters passed to the function are not modified within it. It can also be used to qualify member functions, indicating that the member function does not modify any member variables.

    • Qualifying Function Parameters: This ensures that the parameter remains unchangeable within the function body, which is especially relevant for reference passing.

      cpp
      void printAge(const int& age) { std::cout << "Age: " << age << std::endl; // age = 50; // This would cause an error, as age is a const reference }
    • Qualifying Member Functions: If a member function is declared as const, it guarantees that it does not modify any member variables of the class.

      cpp
      class Person { public: int age; explicit Person(int age) : age(age) {} void printAge() const { std::cout << "Age: " << age << std::endl; } };
  4. Combining with Other Keywords: The 'const' keyword can be combined with other keywords like 'constexpr' to define compile-time constants, which aids in optimizing program performance and resource utilization.

    cpp
    constexpr const int fixedAge = 40;

By appropriately using the 'const' keyword in C++ programming, developers can enhance program readability and safety, prevent accidental modification of data that should remain immutable, and provide the compiler with additional information to optimize the program.

2024年6月29日 12:07 回复

你的答案