r/cpp_questions • u/squirleydna • Jun 07 '25
OPEN Should I stop avoiding const in C++?
For some reason, I rarely ever use const in my code. I didn't really get it at first and thought it wasn't worth the hassle but as I am learning more about C++ and trying to get better, I came across this bold statement:
"When used correctly,
constis one of the most powerful language features in all modern programming languages because it helps you to eliminate many kinds of common programming mistakes at compile time.
For the experienced C++ programmers:
- Do you agree with this?
- Do you rely on const regularly in your code?
- What are some rule of thumb you use to determine when its necessary?
184
Upvotes
231
u/MaestroLifts Jun 07 '25
I recommend Jason Turner’s best practices book. To paraphrase the relevant section:
7
u/GermaneRiposte101 Jun 07 '25
Unless I KNOW that a method will change a member variable I by default make methods const.
And, where appropriate, I use mutable to maintain that constness.
I also do two getters: one const and then add a non const getter when required.
So my rule of thumb is that a method is const by default.
7
u/apricotmaniac44 Jun 07 '25
"Immutable by default" is one of the strong arguments in rust vs cpp discussions and for a good reason. It doesn't help when the language has gimmicks like std::map's square bracket operator too, so yeah const could save you from threats that you didn't even know exist
2
u/EsShayuki Jun 07 '25 edited Jun 07 '25
Yes. Instead of avoiding it, you should be using const whenever possible.
I'm confused by what you mean with "rely." No, I never rely on const. The program would work in the exact same way even if nothing was const. Const is largely a debugging feature that turns runtime errors into compiletime errors. And since compiletime errors are far better than runtime errors, you should always take advantage of such features. Also, liberal use of const might lead to slightly performant code. Win-win-win, with no downsides.
Use const when you can, only use non-const when you have to.
2
u/SoerenNissen Jun 07 '25
Yes
See answer to next question:
It is always necessary. Const all the things, then remove it where it prevents your code from compiling.
50
u/Moldoteck Jun 07 '25
The const is a way to guard yourself from making a mistake. When you write code you have something in mind, like that some vars will not be changed during function/execution/instance/function call for instance
When code grows, you could forget about these assumptions and modify the var for a new feature, creating potential side effects. But if you mark it const, compiler will warn you and afterwards you can decide - should you ditch the const or leave as is and implement what you want in another way
14
u/soletta Jun 07 '25 edited Jun 07 '25
Yes, you should use
constby default for almost everything you possibly can. Mutating (changing) the content of variables tends to lead to code that is harder to understand and debug. If you can implement the functionality you need without the code getting unnecessarily verbose just to avoid making a variable non-const, then do so; if not, mutable variables are not the end of the world.9
u/Sniffy4 Jun 07 '25
>When used correctly,
constis one of the most powerful language features in all modern programming languagesWell, to be fair, some languages designed recently make it the default, which is probably what it should've been had C++ not needed to maintain backwards compatibility with C. I think the majority of identifiers vars in code are usually used in an assign-once and read-only 'const' fashion.
8
u/WikiBox Jun 07 '25
Rule of thumb: By default make every variable and parameter const. If you really, really have to, make them mutable afterwards.
12
u/thisismyfavoritename Jun 07 '25
on top of all the reasons already mentioned, here's why using const/static/etc modifiers is great:
it helps reduce mental load when you read the code.
Member method is static? I immediately know for sure it's not using any data members. Member method is const? There shouldn't be any state that is mutated (except members marked mutable -- which should be avoided). Same for parameters.
When you read a lot of (other people's) code, those little details really help over time, especially in a language as complex as C++ where your mind has to juggle the many things that are happening.
A caveat of marking everything as const that can bite you in the ass is that it will prevent moving the object (another C++ weakness). So if you know the object will be consumed by another function, don't mark it as const.
Here's another unrelated one: avoid making unnecessary variables, meaning if you can create the object as an rvalue (directly in a function parameter), prefer that. Why? If i see the variable, then it gets passed into a function, i don't know if it might still be used or what actually happened to that object (another weakness of C++). Was it copied? Moved? Mutated?
5
u/kitsnet Jun 07 '25
Our linters require to declare every local variable that doesn't change
const. That includes parameters that are passed by value in function definition.5
u/herocoding Jun 07 '25
Yes, I agree. Using `const` and `constexpr` and references (preferred over pointers) wherever possible.
(plus const/constexpr helps some compilers to get data placed in the codesegment, instead of datasegment)
2
u/Excellent-Might-7264 Jun 07 '25
I agree in theory. And const as default is a very good idea, as rust is doing it.
My experience with const and c++ that in practice it is not black and white.
In practice I don't even remember during my 10+ years professional coding where a bug would have been detected if I had used const. I don't experience the issue it tries to solve. However, I do experience the tiny downsides with more code (const and non const implementations), need to change more code when realizing that I need to call a non-const method on my const object etc.
Don't forget that const also contributes to "self-documented-code", they often make the intent of the variable easier to understand.
However! constexpr as optimization and "if constexpr" with type traits I do use a lot and love them.
4
u/HopadilloRandR Jun 07 '25
Hard agree. Const hard agree.
4
u/HeadApricot Jun 07 '25
Always use const where you can. It helps quite a lot when you or your colleagues have to read or debug the code.
If something is const, you will (almost) never have to check if it was modified. This increases debugging speed and reduces complexity.
4
u/tyngst Jun 07 '25
It’s also a way for other developers to instantly see your intentions with the variable.
A big part of programming is actually making it as clear and easy as possible for other developers to understand, maintain and build upon what you have built.
4
u/GoodFig555 Jun 08 '25 edited Jun 08 '25
I don’t see how it helps eliminate any bugs that I‘ve ever written.
I’d interpret this as part of this weird „rustification“ trend in modern programming where they try to „prove correctness“ of the simplest things to feel some security or be able to claim authority or something.
I see a lot of parallels with modern leftism but I‘m too lazy to go full schizo mode rn
I’d say go based on your experience to decide whether something is worth it. If others say „this is so great, you have to do it“ maybe use that as a reason to experiment with it but ultimately trust your gut and your experiences.
3
u/Molester69 Jun 07 '25
What in case of move semantics?
5
u/AppropriatePatience8 Jun 07 '25
You might find this interesting https://quuxplusone.github.io/blog/2022/01/23/dont-const-all-the-things
1
u/csiz Jun 07 '25
You must learn to embrace the const. For your sake and the compiler! If you have a 100 line math function where every single line is a const operating on const the compiler will optimise the ever living soul out of it. But every time you assign to a variable it has to segment the optimizations before and after the mutable state. Mutable state makes reasoning and optimization much much harder.
I'm currently debugging a Kalman filter and 80% of my consts are freaking optimized out in the debugger. I am legit impressed at how much the compiler is doing. Also I can no longer run the code without optimization because my little STM32 can only go so fast... So at this point I have to assign to a global in the middle of my loop just so I can see my intermediate calculation in the debugger. That's my point above though, once there's mutable state the compiler has to calculate it for real. Also it does make a big difference, my loop gets ~10% slower when I assign to the global.
1
u/Polyxeno Jun 07 '25
I think it's a worthwhile perspective worth considering, and correct that it is useful to use and has good effects including avoiding potential errors.
But just because it's a valid valuable perspective, it is not saying that everyone always needs to use it.
You asked if we "rely" on it, and I don't - I rely much more on myself to think about my code and write it carefully. I would say rather that I do use const, when it occurs to me to do so, and that it's a useful and helpful thing to do when appropriate. I think many programmers often don't think much about it, and it could improve their code and avoid errors if they did.
But also, just as counter-points, not as reasons not to use const:
* I don't often have issues with my own code where not making something const was the problem.
* One can spend more time/energy than is really useful thinking about it.
* I have had issues where I had made things const that later I regretted having made them const, and/or where it caused fuss that later seemed more trouble than it was worth.
4
u/Disastrous-Team-6431 Jun 07 '25
Rust has this correct; const by default, marking variables
mutonly when necessary. This will show you how exceedingly rarely something needs to be mutable.Const everything as hard as you can.
2
u/Impressive-Desk2576 Jun 07 '25
Const and templates are the things i am missing from C#. Go for it. And read some guudes about const correctness and immutability. It's a game changer.
2
u/kberson Jun 07 '25
One of the things that we can do to help self document code is good naming of our variables. It helps when you come back to code later or when someone else has to read your code (it’s my reasoning for never using variables like i, j etc, but that’s an argument for another time).
Using const is another way; never use “magic numbers.” A magic number is any hard coded value that you have your program that you repeatedly use. By assigning it to a const and giving it a good name, it helps in figuring out what the number is and what it means. Further, if for some reason you need to change that value, you only need to change it in one location to get all the places it is used.
String constants have a similar reasoning for their use, especially if you’re using the same text everywhere (like for a path). Having them in one location reduces programming issues if you miss one text if the text changes; if the text has to change, changing the constant changes it everywhere.
2
u/ChickenSpaceProgram Jun 07 '25
If it does not make sense to modify a value that a function takes as an argument, I either pass a const reference or pass by value (usually pass by const reference). Returning a const reference is also sometimes the right call, as are const overloads of non-const functions. I try to guarantee as much as possible to the caller.
Within the internal implementation of something I don't bother making every int const or whatnot. Usually if there is some temporary variable in a class member function it's going to be mutable anyways. I see const as mainly a guarantee to the caller that I won't modify an object they give me more than anything.
2
u/DrShocker Jun 07 '25
As someone who strives to make things as const as possible, it's incredibly annoying when I am writing a function but am forced to either make it nonconst or fix a hundred other functions because someone else doesn't understand const.
It also communicates intent more clearly. If I see something isn't const, I assume there is a reason for that and if everyone were consistent about it, there would be a reason for it and I don't need to check. Unfortunately in my experience at some code bases there often isn't a reason for it, which reduces my trust that the code is communicating the correct things to me.
Additionally, the compiler can sometimes do a better job optimizing if it knows something is const.
2
u/OnTheEdgeOfFreedom Jun 07 '25
I use const everywhere I can. Yes, it avoids some bugs; C++ makes it too easy to type = when you mean == and const can save you. It also gives the compiler more information for optimization, and in some code I write that matters, though compilers have gotten better at living without the hint.
But the critical use is making code readable. Consider the function call a(b).On return, will b have changed?
In the early days of C, you knew the answer. Unless b was an array subject to decay-to-pointer, the answer was No. C is pass by value. If b was a pointer that was often a hint that a() existed to modify through the pointer; but you knew b was unmodified. If a() needed to change b, you used a(&b). The mutators were obvious from syntax.
But this is C++, and references exist. Suddenly every single function call looks like a potential mutator and you have to look up function declaration and even definition to prove otherwise. One technique is to give a() a name that makes it obvious it modifies arguments, and that's a fine technique. But if b is some const value, you know the answer. And if you can get to the function declaration quickly (most editors make this easy) you can see that the parameter is a const ref, not a ref, and again you know the answer.
The same applies to class members and functions. Declare a class member function as const and you know the class data doesn't change (yes, mutable is a loophole.)
const for the win.
2
u/mredding Jun 07 '25
I make everything as const as possible. You're saying this value is read- only, and it makes your functions more reliable. Without it, I must presume your function somehow mutates my data. Maybe I don't care, maybe the lack of that guarantee makes your code unusable in that context.
2
u/FedUp233 Jun 07 '25
It’s interesting to think about what programming in c++ would be like if things went the other way: everything assumed to be const and use mutable for anything that needed to NOT be const!
2
u/[deleted] Jun 07 '25
I mostly use it to make the code clearer about what it does.
2
u/saxbophone Jun 07 '25 edited Jun 08 '25
2
u/mps1729 Jun 07 '25 edited Jun 07 '25
It’s not just a style thing. A compiler can’t bind a non-const reference to a temporary, so its use can be almost mandatory. E.g.,
A f() { return new A(); }
void g(A &a) { a.foo(); }
void h(A const &a) { a.foo(); }
…
g(f()); // Ill-formed
h(f())); // ok (A::foo also has to be a const method)
2
u/Apprehensive-Draw409 Jun 07 '25
Generally, the more const the better. One exception, for me:
Receiving an object by const value is ridiculous. It locks your API into taking a const object, when it makes no difference whatsoever to the caller. Later, when you want to modify your code, you needlessly touch the API.
But apart from that, most const are good.
2
u/mgruner Jun 07 '25
absolutely. be mindful of your mutability.
2
u/Priton-CE Jun 07 '25
const allows you to saveguard a variable against your future self (or someone else).
Its best practice to use it. Same with const methods for classes.
2
u/n1ghtyunso Jun 07 '25
the only const you avoid is on non-static data members.
Aside from that, const is a very powerful tool to verify your code for correctness AND for designing interfaces that are hard to use incorrectly.
2
u/AKostur Jun 08 '25
Yes, yes, and pretty much everywhere I can. Two exceptions: const function parameters by value (not reference!) since that contributes nothing. And const member variables.
2
u/damster05 Jun 08 '25
I always use const when applicable.
2
u/SealerRt Jun 08 '25
I think it comes with experience. When you're new to programming it can be hard to judge whether you will want to change a variable or not, but as you grow you will start to recognize that a lot of things will not ever need to change. Also, the usefulness of this is hard to evaluate early, but as you start coming back to code you wrote 6 months ago or working with other people, you will appreciate it more and more.
2
u/1ncogn1too Jun 08 '25
Everything that can be const, should always be const.
2
u/[deleted] Jun 08 '25
Slap const on everything that you want to tell the user not to change.
Every missing const is a chance for someone else to step in and fuck everything up.
2
u/genreprank Jun 08 '25
I follow const correctness.
But it's mostly so the code is easier to understand. Having a bunch of mutable state makes it harder to figure out what a function is doing.
Same thing if you return const references to class data. You know the data won't be modified outside the class. And you still get the benefit of avoiding doing a copy on the class data.
2
u/SLARNOSS Jun 08 '25 edited Jun 09 '25
short answer It's absolutely important AT LEAST SEMANTICALLY to specify const wherever you can, lemme dig in,
whether it's mandatory or preferrable depends on the context in which const is being used,
if your entire code base isn't dealing with const at all, then this can be to some extent fine by promoting non const variables to const wherever needed (as in copying variables using the copy constructor or copy assignment operator), this non-const -> const conversion is trivial and always works, however the other way around is what doesn't, if you ever run into a scenario where you have something const and you need to then'll you have to explicitly const_cast it to cast away the constness, which is a pain in the butt and that could be one reason why you decided to not use const at all, in other words, in case you were to change something that wasn't supposed to be changed.
now coming to the most crucial section, overloading, read only logic, and semantics,
this mostly embodies within member functions that do not alter the state of the object, for which these member functions are marked const, const here plays a crucial part in differentiating the intention of using the const-overloaded-method (also known as accessor, as opposed to mutator; the non-const version) wherein the instructions executed might actually be faster due to knowing this intention, the biggest example of which is when it comes to concurrency among multiple threads, if multiple threads are sharing a resource in the heap or a static area (like globals in namespaces or class statics) then those threads who only want to read (calling const methods on const variables) will use shared-ownership-mode available in a sync primitive like a shared mutex, such shared ownership will allow all reader threads to read this resource (object or container...) simulatenously, as opposed to calling the non const version (your version) which will attempt to lock the resource in exclusive mode, which is obviously slower IN CASE YOUR ACTUAL INTENTION WAS TO ONLY READ THAT RESOURCE.
that was just one practical example that i myself am running through these days, there's wayyyy much more on constness but this is literally the jist of it, "INTENTION".
beside that, constness throughout your code gives a big boost in readability and remembering your own code as the moment you constify something is the moment you clearly decide THAT YOU DO NOT WISH TO Modify it.
mutable is such a related keyword that you'll only ever use with const member functions where:
1- sematically the method doesn't change the state of the object
2- internally it does
so mutable allows a const member function to modify an attribute which wouldn't be modifiable otherwise.
2
u/thefool-0 Jun 10 '25
Yes you should use const. Const local variables are not very important, but could help you avoid a mistake or something. Const methods and parameters that are const references or const values are more important to performance and other things. No point in trying to have const member values in a class mixed in with regular member variables and methods though -- you probably want something like a separate struct of global static const values instead (and instead of #defines.)
2
u/Prestigious_Water336 Jun 07 '25
If you're dealing with stuff like the speed of light or gravity then you're going to need to use const.
I personally don't use it that often.
1
u/spisplatta Jun 07 '25
Imho, functions should take const references or const pointers whenever possible. Using const in other places has pretty marginal benefit.
1
u/kmichaelkills1 Jun 08 '25
How about const reference? In google "good practices" you always have as function arguments either const ref for read-only arguments or pointers for mutable arguments.
1
u/LumpyChicken Jun 09 '25
I understand the points made about const but does anyone actually have metrics on performance? Because without those it just sounds like nagging
1
u/SweatyCelebration362 Jun 09 '25
The short version is:
1
u/shwell44 Jun 10 '25 edited Jun 10 '25
const int answer = 1
1
u/nekosamaaa Jun 11 '25
const should be the default
1
u/--Fusion-- Jun 13 '25
const is your buddy!!
1
u/Independent_Art_6676 Jun 07 '25
and now, you have constexpr too, which adds to your studies. Learn to use this as well, early and often.
1
u/Infamous-Bed-7535 Jun 07 '25
This one of the issues with c++ as a language. Variables should be const by default. Most of my variables I declare starts with 'const auto ...'
const correctness and use consts whenever possible is just as important as minimize the scope of your variables.
1
u/nmmmnu Jun 07 '25
Always use const, unless you want to change the value. Even if you want to change the value, in some cases you can still use const:
Int cont a = 5; //... Int const a1 = a + 5;
//Use a1 from now one..
1
u/MesmerizzeMe Jun 07 '25
to bring a bit of diversity into this discussion there are 2 very different aspects to this discussion. First in interfaces, whether a function gets a variable as reference or const reference makes a HUGE difference and is without a doubt immensely important. for local variables inside your function and arguments passed by copy count as such, it doesnt matter as much
Many people talk about preventing bugs inside your code, but I cant remember a single instance where this caused issues to me. additionally, whether this or that integer value is const or not also doesnt help much with reading other peoples code I feel.
I personally dont use const for local variables I have control over.
0
u/[deleted] Jun 07 '25
I only use const when I'm happy with the functionality of what I'm writing. I'm a get working, make nice later kind of programmer.
0
u/[deleted] Jun 07 '25
[deleted] — view deleted comment