Ch2.8: const

What is const?

The keyword const marks a variable as immutable: once initialized, its value cannot change. It improves correctness and clarity, but it does not affect performance.

The Rule of const

The full rule is: const applies to what is on its left. If there is nothing on the left, then it applies to what is on its right.

Because of this, we can simplify the rule to: const applies to the left. Full stop.

Therefore, the preferred style is to write T const instead of const T. The type comes first, then the qualifier.

Some people believe tools like clang-tidy should even provide a toggle to warn users if they write const T instead of T const.

Examples


#include <cstddef>
#include <cstdint>

::std::int32_t  const a{42};     // constant 32-bit integer
::std::size_t   const n{100};    // constant size_t
double          const pi{3.14};  // constant double
char            const nl{'\n'};  // constant char

// Do NOT write: const ::std::int32_t wrong{42};
// Preferred:    ::std::int32_t const a{42};

const and Performance

A common misconception is that using const makes your code faster. This is false. Modern compilers already perform optimizations based on usage and lifetimes, regardless of whether a variable is declared const.

The purpose of const is correctness and clarity — it prevents accidental modification and communicates intent. It is not a performance feature.

For more discussion, see The Art of Machinery: C const isn’t for performance .

Key Takeaways