Isn't "const" redundant when passing by value?

C++ConstantsPass by-Value

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel ScoccoView Question on Stackoverflow
Solution 1 - C++Ernest Friedman-HillView Answer on Stackoverflow
Solution 2 - C++psurView Answer on Stackoverflow