Difference between const reference and normal parameter

前端 未结 7 1950
我寻月下人不归
我寻月下人不归 2020-11-28 01:09
void DoWork(int n);
void DoWork(const int &n);

What\'s the difference?

相关标签:
7条回答
  • 2020-11-28 01:56

    There are three methods you can pass values in the function

    1. Pass by value

      void f(int n){
          n = n + 10;
      }
      
      int main(){
          int x = 3;
          f(x);
          cout << x << endl;
      }
      

      Output: 3. Disadvantage: When parameter x pass through f function then compiler creates a copy in memory in of x. So wastage of memory.

    2. Pass by reference

      void f(int& n){
          n = n + 10;
      }
      
      int main(){
          int x = 3;
          f(x);
          cout << x << endl;
      }
      

      Output: 13. It eliminate pass by value disadvantage, but if programmer do not want to change the value then use constant reference

    3. Constant reference

      void f(const int& n){
          n = n + 10; // Error: assignment of read-only reference  ‘n’
      }
      
      int main(){
          int x = 3;
          f(x);
          cout << x << endl;
      }
      

      Output: Throw error at n = n + 10 because when we pass const reference parameter argument then it is read-only parameter, you cannot change value of n.

    0 讨论(0)
提交回复
热议问题