What is const keyword in C++: Explanation and Examples
const keyword in C++ is used to declare variables or objects whose value cannot be changed after initialization. It helps protect data from accidental modification and makes code safer and easier to understand.How It Works
Think of const as a 'do not change' sign for a variable. When you mark a variable as const, you tell the computer that this value should stay the same forever after you set it. This is like writing a rule on a sticky note that says "Don't touch this!" so no one accidentally changes it.
In C++, const can be used with variables, pointers, function parameters, and even member functions. It acts like a promise that the value won't be modified, which helps prevent bugs and makes your program more reliable. For example, if you have a number that should never change, marking it const ensures that no part of your program can alter it by mistake.
Example
This example shows how to use const to protect a variable from being changed:
#include <iostream> int main() { const int days_in_week = 7; // This value cannot be changed std::cout << "Days in a week: " << days_in_week << std::endl; // days_in_week = 8; // This line would cause a compile error return 0; }
When to Use
Use const whenever you have a value that should not change after it is set. This is common for fixed values like mathematical constants, configuration settings, or any data that must remain stable throughout the program.
Also, use const in function parameters to show that the function will not modify the input. This helps other programmers understand your code better and avoid mistakes.
For example, if you pass a string to a function and you want to make sure the function does not change it, declare the parameter as const std::string&. This is like telling the function, "You can look at this, but don’t change it."
Key Points
constmakes variables read-only after initialization.- It helps prevent accidental changes and bugs.
- Use
constfor fixed values and safe function parameters. - Can be applied to variables, pointers, references, and member functions.
Key Takeaways
const keyword protects data from being changed after it is set.const to make your code safer and easier to understand.const to variables, function parameters, and member functions when you want to prevent modification.const variable causes a compile-time error.const helps communicate your intent clearly to other programmers.