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:
-
Defining Constant Variables: The 'const' keyword can be used to define a constant variable, guaranteeing that its value remains immutable after initialization. For example:
cppconst int MAX_AGE = 100;In this example,
MAX_AGEis defined as a constant with a value of 100, which cannot be modified later in the program. -
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.
cppconst 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.
cppint age = 30; int* const ptr = &age; *ptr = 31; // Allowed // ptr = &MAX_AGE; // Error, ptr is a const pointer
-
-
'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.
cppvoid 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.
cppclass Person { public: int age; explicit Person(int age) : age(age) {} void printAge() const { std::cout << "Age: " << age << std::endl; } };
-
-
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.
cppconstexpr 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.