AR7 AR7 - 1 year ago 59
C++ Question

Are there any downsides to marking all variables you don't modify const?

After much googling I've found a lot about marking functions and their parameters as

, but no guide on marking variables as

Here's a really simple example:

#import <string>
#import <iostream>

void example(const std::string& x) {
size_t length = x.length();
for (size_t i = 0; i < length; ++i) {
std::cout << << std::endl;

int main() {

Why not make

size_t length = x.length();

const like

const size_t length = x.length();

by convention?

I know such a small, simple example really doesn't show any huge benefit to this, but it seems like it'd be helpful in a larger codebase where you might accidentally mutate a variable you shouldn't have mutated.

Despite that benefit, I don't really see it used that much (in the C++ codebases I've seen) or mentioned nearly as much as making functions and their parameters

Is there some downside to doing this other than having to type 5 extra characters? I haven't found much on the topic, and I don't want to shoot myself in the foot if it's a problem having so many consts.

Answer Source

There are no downsides to marking variables you don't modify const.

There are some up-sides though: the compiler will help you diagnose when you unintentionally modify a variable you shouldn't/didn't mean to and the compiler may (although due to the language having const_cast and mutable this is rare) generate better code.

So, I'd advice; use const where you can. There are no downsides and your compiler can potentially help you spot bugs. No reason not to (except for a bit of extra typing).

Note that this extends to member functions as well. Make them const when you can - it lets them be used in more contexts and helps users reason about the code ("calling this function won't modify the object" is valuable information).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download