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:
#include <string> #include <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.
The most important reason is to avoid bugs. By marking something const , you allow the compiler to catch any attempts to change it. For example, imagine if some variable is passed by reference to a function that changes it. If you marked that variable const , the compiler will catch that.
Changing Value of a const variable through pointerThe compiler will give warning while typecasting and will discard the const qualifier. Compiler optimization is different for variables and pointers.
The constant variable values cannot be changed after its initialization.
To start you probably know that const can be used to make either an object's data or a pointer not modifiable or both. However you can also use the syntax: Object const *obj; // same as const Object* obj; The only thing that seems to matter is which side of the asterisk you put the const keyword.
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 advise; 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With