Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: The const Mantra

📅 2010-Jul-24 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ const, cpp ⬩ 📚 Archive

 

The const mantra to keep in mind while writing C++ code is to make everything const, that is, as much as possible. Typing 5 extra letters everywhere might seem like extra work, especially to C gurus, but the paybacks of const can be quite significant over time. It is one extra nail hammered into the code to ensure that the code behaves exactly as envisioned in the head of the programmer. Once the vision of the programmer has been converted to code, const helps in ensuring the correctness of this code by pushing the burden of this checking onto the compiler. Thus bugs can be caught much earlier, at compile time. The const code will also behave much nicer with STL and other libraries that give special emphasis to const. They might have faster and/or more robust implementations for const.

Here are some simple guidelines to const the code:

void FooContainer::append( const FooContainer& );
void FooContainer::display() const;
void FooContainer::displayWithIndex( const FooVector& ) const;
void FooContainer::display() const
{
    const int max = size();
    // ***
}
for ( FooVector::const_iterator i = fooVec.cbegin(); i != fooVec.cend(); ++i )
{ /***/ }

Note that injecting your code with the const vaccine will have some initial side-effects. The const introduced in one method starts to spread virally through your code, giving const related compile errors. This forces you to re-think the assumptions of your code, re-factor and re-write a lot of your code. Yes, this is good for you and your code. Go gain your const-vision! 😀


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧