Use of const for non-reference parameters

J

Jorgen Grahn

I am one of those few programmers who think that constness should be
the *default*, and non-constness the exception (iow. only used when you
truly need the variable to be non-const).

Hm, are we really few, if we look at C++ users only?
That is, every time I declare
a variable, I make it const unless that variable needs to be changed.
While the usefulness of this is admittedly somewhat low, it still serves
as both documentation ("this variable will not be modified during the
rest of this function") and minor code correctness checking (if a
variable is intended to not to be modified, if you get an error that
you are in fact trying to modify, then you either have a design error
in your code, or you need to "re-document" your variable declaration).

IMHO you underplay the usefulness. If I have a long function, I find
that I can apply const to maybe 70% of its variables. That makes it
much more obvious what the changing state is, and readability increases.
It is also remotely possible that declaring non-changing variables as
const might in a few cases help the compiler to optimize better (although
I don't have any concrete evidence of this right now).

Neither do I. I tend to believe that either the optimizer has enough
information to see that the variable doesn't change (so it doesn't
need your const), or it doesn't have enough information to rule out
aliasing (so it can't use your const).
I have to admit, though, that I seldom declare non-changing function
parameters const because it makes the function declarations longer
(especially for functions taking many parameters). I have been slowly
changing this, though. (After all, brevity should never be preferred
over quality.)

I use const at least as much for parameters. They benefit at least as
much as ordinary variables. More than most, because they are in scope
throughout the function.

/Jorgen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top