C++快排函数调用里 用 const修饰比较时的变量有什么作用嘛?
PHPz
PHPz 2017-04-17 12:06:02
0
3
907
PHPz
PHPz

学习是最好的投资!

reply all(3)
PHPzhong

The function of const here is to ensure that the modified parameters are not modified inside the function,

If it is passed by reference int cmp(const int &x,const int &y), the actual parameters will be passed directly to the function, eliminating the process of copying the actual parameters to the formal parameters, and then using const to ensure that the function cannot modify the actual parameters passed to it. Participation can improve efficiency.

But in your code example, int cmp(const int x,const int y), you still have to copy the actual parameter value to the formal parameter first, and then compare the formal parameters in the function, so the efficiency is not improved. In addition, this form of function use const is completely meaningless. Even if the function modifies the value of the formal parameter, because the formal parameter is a copy of the actual parameter, it will not affect the actual parameter at all. Use const to ensure that the function cannot modify the value of the formal parameter. What's the point?

For detailed information, please read my article: http://segmentfault.com/a/1190000003696397

In addition, I suggest you read more books on C and C++, mainly about pointers and memory. The answers here are only relatively one-sided. I hope you can read more books to get a systematic understanding

"C and Pointers", "C Expert Programming", "Effective C++"...there are quite a lot of books

Peter_Zhu

They are all passed by value and do not improve efficiency.

It feels like this is unnecessary, because a copy is made during the parameter transfer process, and modifying the parameters does not modify the original value.

阿神

The answer above is very detailed. Another function is that const can improve the readability of the code. When you see const, you know that the variable will not change.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!