95

I was reading my C++ book (Deitel) when I came across a function to calculate the volume of a cube. The code is the following:

double cube (const double side){
    return side * side * side;
}

The explanation for using the "const" qualifier was this one: "The const qualified should be used to enforce the principle of least privilege, telling the compiler that the function does not modify variable side".

My question: isn't the use of "const" redundant/unnecessary here since the variable is being passed by value, so the function can't modify it anyway?

BЈовић
  • 62,405
  • 41
  • 173
  • 273
Daniel Scocco
  • 7,036
  • 13
  • 51
  • 78
  • 8
    The meaning of `const` here is that you cannot modify `side` parameter inside `cube()` method to avoid unexpected behavior. – Tomasz Nurkiewicz Jan 03 '12 at 15:09
  • 3
    sometimes things are more about of 'good practice' than of necessity. I think this is one of those times. – destan Jan 03 '12 at 15:11
  • 4
    I think the answers did a good job of explaining why you would do that, but I'll just add that to an external caller, the `const` *is* redundant and isn't part of the function's signature. That means you can leave it off in the function declaration without changing anything. You can also remove it later if for some reason you want to make your code less maintainable, and it won't affect the calling code. – Matthew Crumley Jan 03 '12 at 16:37
  • 2
    One thing I dislike about it is that it forces me to either (a) make the `const` visible in the declaration, where it's not meaningful, or (b) make the declaration and definition inconsistent. I suppose the solution is to get over my qualms about (b). – Keith Thompson Jan 03 '12 at 18:15
  • In Java, the `final` keyword in the same location is required for closures to work correctly when declaring an anonymous class inside the function. Might it be the same for C++? – Izkata Jan 03 '12 at 20:33
  • What I'm wondering is why they aren't passing by const reference. – Marcel Besixdouze Aug 07 '20 at 01:19

2 Answers2

128

The const qualifier prevents code inside the function from modifying the parameter itself. When a function is larger than trivial size, such an assurance helps you to quickly read and understand a function. If you know that the value of side won't change, then you don't have to worry about keeping track of its value over time as you read. Under some circumstances, this might even help the compiler generate better code.

A non-trivial number of people do this as a matter of course, considering it generally good style.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
56

You can do something like this:

int f(int x)
{
   x = 3; //with "const int x" it would be forbidden

   // now x doesn't have initial value
   // which can be misleading in big functions

}
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
psur
  • 4,400
  • 26
  • 36