Why variables should be made constant
If a variable can be made constant, it generally should be made constant.
- It reduces the chance of bugs. By making a variable constant, you ensure that the value can’t be changed accidentally.
- It provides more opportunity for the compiler to optimize programs. When the compiler can assume a value isn’t changing, it is able to leverage more techniques to optimize the program, resulting in a compiled program that is smaller and faster.
- Most importantly, it reduces the overall complexity of our programs. When trying to determine what a section of code is doing or trying to debug an issue, we know that a
constvariable can’t have its value changed, so we don’t have to worry about it as much.
Every moving part in a system increases complexity and the risk of defect or failure. Non-constant variables are moving parts, while constant variables are not.
Applying const
Getters are easy candidates. In the example below, const is applied twice.
When it’s applied to the return type, it means the function returns non-mutable reference to std::string.
The const directly before the function body is a promise that this function will not modify m_Name.
const std::string& Character::GetName() const {
return m_Name;
}
Parameters can also be made const. In this case, the function is promising the compiler it won’t modify the parameter.
Additionally, it conveys semantic information about a function. In the example below, since CalculateDodgeChance only has read access to the parameter, we are certain it’s not going to modify it.
int CombatEngine::CalculateDodgeChance(const StatBlock& defenderStats) {
return m_BaseDodgeChance + defenderStats.GetAgility() / 3;
// (3 AGI = 1% dodge)
}
Takeaway
If a variable doesn’t need to change, label it const. This reduces the number of moving parts in the system, leading to simpler programs and easier debugging.