In C++, the `const` keyword is used to define constant values or to indicate that a variable's value will not be modified. This is particularly useful for improving the safety and readability of your code. By declaring variables as `const`, you can prevent accidental changes to them.
There are several common uses of `const`:
Here is an example demonstrating the use of `const` in different contexts:
const int CONSTANT_VALUE = 100; // Constant variable
void exampleFunction(const int *ptr) {
// Function that takes a pointer to a constant integer
// *ptr = 200; // This would cause a compilation error
std::cout << *ptr << std::endl;
}
class MyClass {
public:
void regularFunction() {
// Modify member variables
}
void constFunction() {
// Cannot modify member variables
std::cout << "This is a const function" << std::endl;
}
};
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?