Home  >  Q&A  >  body text

C++快排函数调用里 用 const修饰比较时的变量有什么作用嘛?

PHPzPHPz2764 days ago939

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-17 12:08:02

    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

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 12:08:02

    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.

    reply
    0
  • 阿神

    阿神2017-04-17 12:08:02

    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.

    reply
    0
  • Cancelreply