Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

After 15 years of C++, I've still haven't learn to love using const. I understand it's use, but I've never actually been in situation where being const correct would have avoided the problem I was facing.

So how did you come to love benefits of consts?

share|improve this question

closed as too broad by gnat, 17 of 26, Mason Wheeler, MichaelT, Ampt Jan 29 at 15:59

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

I think const correctness is more of being correct than a tool to solve a problem like a if constrcut or a sizeof operator. – legends2k Sep 30 '10 at 8:25
"The reason that const works in C++ is because you can cast it away. If you couldn't cast it away, then your world would suck." - Anders Hejlsberg – Mason Wheeler Oct 4 '10 at 20:14
const is also a C type modifier and has been since the first ANSI C standard. – Huperniketes Oct 12 '10 at 11:36
Being spoiled by Java/C#, I am a paranoid type who loves to leave asserts any chance I get. What can go wrong will go wrong. If there is a compile-time or a run-time assist, then count me in! I became a convert as soon as I heard about it 3-4 times, and followed a portion of this link (enough to see the syntax, I did not need to read about the why): Just because something has not blown up in my face yet ... it takes little effort to be const correct, and it does not hurt. Check out Joel's thoughts: – Job Dec 12 '10 at 15:57

I've never been a proponent of object-oriented programming, and if anything I've grown less so the more I learn about programming in general. As I've studied different programming paradigms, I've realised that immutability is one of the central concepts of program design, affecting software written according to any philosophy. It's hugely important in functional programming, with implications in optimisation and concurrency on top of the simple safety guarantees.

Basically, everything that can be immutable probably should be, unless you've got a good reason for mutable state. In my experience, writing programs in any language in pursuit of this goal leads to safer, better code. You have nothing to lose by using const where applicable—immutability is free!

(Incidentally, I've toyed with the idea of creating a fork of GCC for a dialect of C++ in which all types are const unless explicitly qualified as mutable. If there's support for such a thing, I will totally commit to maintaining and using it.)

From an OO standpoint, immutability enforces encapsulation by preventing unrestricted write access. It reduces coupling between classes because immutable objects must fully manage their own state and thus behave like ordinary values. Const correctness significantly eases the process of proving program correctness, especially in the context of concurrent programming. With C++ reference and C++0x rvalue reference semantics, you can make use of immutable objects without worrying about the overhead of copying them all over the place. Further, the compiler can work some pretty amazing optimisation magic if you're working with mostly immutable objects.

I know it sucks to type const everywhere, but you rapidly get used to it, and the benefits become apparent over time in terms of reliability and maintainability. I'm not a brilliant writer, and it seems to be a proven difficult task to make a case for it, but I know that const correctness has been immensely helpful to me as a developer when designing and implementing programs, and I think experience is the best teacher in this regard.

share|improve this answer
You basically just said that const correctness is a Good Thing. You said that it "leads to safer, better code". Can you say why? – David Reis Sep 30 '10 at 5:58
I'm totally in the immutability camp, my favorite language is Erlang. But I would argue that immutability via const in C++ is not really free. There are downsides like less readable code, const and non const versions of the same method, or casting const away cause "there was just no other choice". – grok Sep 30 '10 at 6:47
I'd advise not just using mutable, since it has a clear meaning in terms of const correctness. It means that this data object can change in ways that do not affect object behavior, and allows things like caching answers. Make up another keyword. – David Thornley Sep 30 '10 at 15:26
@David Thornley: For consistency's sake, mutable is the logical choice. void alter(mutable Point&) makes sense, as does mutable int foo for a local variable, and neither of these conflicts with the existing language or the existing use of mutable. Also, Object mutable* mutable looks scary enough to be a warning about whether it's necessary or correct. – Jon Purdy Sep 30 '10 at 15:36
If you ever do the fork, consider going with CLang instead - should be less painful. – g.f Oct 31 '10 at 14:42

Being const correct emphasises the correctness of the design which I treat close to a similar issue which is not using cast operators; so not using cast and being const correct, minimal usage of mutable - all of these are pointers to measure how good the design is but not the actual tools to solve the overall problem in hand.

P.S.: I got totally convinced of const once I understood the correctness in using it ;)

share|improve this answer

Well I wasn't convinced until I tried to embrace the philosophy.

I first started by putting const to really read-only members of my most basic class members and member functions arguments.

From there, I couldn't compile anymore. Then I persevered in going in the code using those basic classes, see if the previously const additions were really legitimate compared to the use I made of them. It helped me fix some bugs on the way as I added constness to other parts of the code.

It's contagious. Most of the code got even more constness and I found easier to debug it because it makes you confident that the compiler will stop you if you start modifying something you shouldn't.

Once I got the application running again, it was faster (had to change some algorithms that I've discovered weren't right for the job), with a lot less bugs and easier to understand when reading the code.

I was convinced.

Now, I think that it's even better when you're using a lot of assertions in addition to constness because it makes you feel confident when you have to write new code or modify the current code. You know the compiler will stop you if necessary. It lets you forget about having to check everything you shouldn't modify and then you have more thinking time for more business-specific thinking, or architectural thinking.

share|improve this answer
+1 for contagious which essentially means you either must become a const convert or completely avoid it altogether. – Martin Wickman Dec 12 '10 at 11:51
You also need to not rely on libs that don't do const correctness. Your approach doesn't work when it means you can't call any of the gui functions because they aren't const - or you need to cast it away in every gui call. – Martin Beckett Mar 3 '11 at 16:51
+1 for "found it easier to debug", I use const even for local variable that I know I won't need to change, this way when reading code I can skim over a if or a for or whatelse: my variable is a constant, I know it won't change! I could not care less about optimizations, but I have a limited brain, and few level of indents + const-correctness help greatly! – Matthieu M. Mar 3 '11 at 19:30
@MatthieuM.: Ever considered switching to Haskell? ;-) – Giorgio Jan 29 at 16:59
@Giorgio: I've explored it, even went so far as buying "Real World Haskell". To be honest I am not thrilled with laziness by default and the many cryptic operators that have sprung up. – Matthieu M. Jan 29 at 18:04

The advantage of const correctness is that it imposes a discipline on the program, and makes it easier to reason about parts of the program.

The discipline is that you need to know where something might get changed. The corresponding advantage is that it's easier to see what a piece of code does when you can tell what might be changing the state.

share|improve this answer
"Programs must be written for people to read, and only incidentally for machines to execute." - Abelson & Sussman, SICP – Brandon DuRette Nov 1 '10 at 14:20

I see two main reasons for writing const-correct code. One is that the compiler is your friend, and by using const you let it warn you of potential bugs. The second reason is that const-correctness makes code more readable. For example, you always know which function arguments are inputs and which are outputs. You also know which member functions modify the object and which do not. You know these things instantly without having to read through the code. This, of course, assumes a very judicious use of const_cast.

share|improve this answer

I was a convert as soon as I knew it was possible. It made sense to me from a 'good programming style' standpoint. There are various reasons for why it is good practice to be const correct:

  • Readability and understanding. If I'm reading someone else's code and a function takes a const reference as a parameter I know that the parameter is only meant to be used as a read-only variable. This is a massive win especially if the code is multi-threaded environment.
  • The compiler can make use of the const qualifier to aid its optimization passes.
  • Say I have an object of class A in a situation where I don't want it to change. Then the only member functions that can be called for that object are those that are const.
share|improve this answer

To summarize two points that have be covered in other answers, and add a new one:

  • const documents the code to users of your API. It forms a contract between a function and its caller, that the function will not modify its parameters. (Please note that const_cast does not enable a function to change its parameter, it allows passing that parameter to other functions that do not modify their parameters but forgot the const annotation.) It is also useful within functions/loop/etc because it aids understanding much the same way as a loop invariant.

  • const documents your intent to the compiler. Finding mistakes at compile-time is always better than waiting for that piece of code to run.

  • const is necessary for type safe polymorphism. Pointers (in all their forms, not just raw pointers) are only covariant if they are const (Note: not the same as "pointer to const"). Covariance requires a read-only interface, and contravariance requires a write-only interface.

The second of these I learned first. I started with const only on the target of pointer and reference parameters, until I started seeing the benefits of catching errors earlier, and starting using it on locals, etc.

Then I learned that most #defines can be replaced (in C++) by global constants, with added benefits of type-safety. So I used it there too.

Finally I took a class on type systems and lambda calculus, and learned that const and non-const types are fundamentally different (since they support different operations), and since then I've never even considered writing C++ code without heavy use of const.

share|improve this answer

Here's my 5 cents of what I haven't seen others mention. When passing around variables you do not want to be passing by value, unless you really need to, to avoid extra constructions and destructions and copies. So unless you really must pass by value, using references everywhere, even if you do not mean to change the passed value is a significant performance increase. For this reason, when you have functions taking references of all its arguments, you need to let the caller know what the function will not be modifying.

Its the same principle, but I just wanted to add a practical reason of using const.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.