Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isn't "const" redundant when passing by value? [duplicate]

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?

like image 666
Daniel Scocco Avatar asked Jan 03 '12 15:01

Daniel Scocco


People also ask

Is it good practice to use const?

const is a one-off assignment variable. Reasoning about a const variable is easier (compared to let ) because you know that a const variable isn't going to be changed. A good practice when choosing the declaration type of variables is to prefer const , otherwise use let .

Should I always use const C++?

Yes, you should use const whenever possible. It makes a contract that your code will not change something. Remember, a non-const variable can be passed in to a function that accepts a const parameter. You can always add const, but not take it away (not without a const cast which is a really bad idea).

Is it faster to use const?

No, const does not help the compiler make faster code. Const is for const-correctness, not optimizations.

Is const useless?

Adding const to a value-type parameter in the function declaration is useless. The caller won't care whether the parameter is modified or not because the caller's data won't be affected in any way.


2 Answers

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.

like image 179
Ernest Friedman-Hill Avatar answered Oct 04 '22 02:10

Ernest Friedman-Hill


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  } 
like image 21
psur Avatar answered Oct 04 '22 00:10

psur