当通过值传递时“ const”不是多余的吗?

我在读 C + + 的书(Deitel)时,偶然发现了一个计算立方体体积的函数。密码如下:

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

使用“ const”限定符的解释是: “ const 限定符应该用于强制执行最小特权原则,告诉编译器函数不修改变量端”。

我的问题 : 这里使用“ const”不是多余的/不必要的吗? 因为变量是通过值传递的,所以函数无论如何都不能修改它?

25715 次浏览

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.

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


}