AR7 AR7 - 3 months ago 6
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

const
, but no guide on marking variables as
const
.

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 << x.at(i) << std::endl;
}
}

int main() {
example("hello");
}


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
const
.

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

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).