C++ passing by reference or by value?

This question already has an answer here:

  • What's the difference between passing by reference vs. passing by value? 18 answers

  • When passing a variable by reference, whatever changes you make to it in the function are reflected back in the calling function.

    On the other hand, when you pass a variable by value, the changes made to it are local, and hence not reflected in the calling function.

    For example,

    #include "iostream"
    using namespace std;
    
    void function1(int &x, int y) // x passed by reference
    {
        x+=y;
    }
    
    void function2(int x, int y) // x passed by value
    {
        x+=y;
    }
    
    int main()
    {
        int x=10;
        function1(x, 10);  // x is passed by reference (no & while calling)
        cout << x << endl; // 20
        function2(x, 1000);// x is passed by value
        cout << x << endl; // 20
    }
    

    Notice that whatever value of y you pass in the call to function2 does not make any difference to the second cout statement.

    You do not decide whether to pass values or references in main . The function definition decides that for you. Irrespective of pass by value or pass by reference, the format of calling a function remains the same.


    void getCoefficients(double &a, double &b, double &c);

    This says, "I take 3 parameters - all of the type double & (reference to a double). Reference is quite a lot confused with pointers, so I recommend you read this up first.

    Let's call the a,b,c inside the main as main_method_vars.

    When you call getCoefficients , whatever this function does to the passed variables inside it, is reflected on the main_method_vars. Actually, this method works with the main_method_vars.

    If instead you have void getCoefficients(double a, double b, double c) , this means that whenever you call this method with the main_method_vars, this method will copy the values of a,b,c and work with new copies, instead of working with the original passed copies to it.


    void getCoefficients(double &a, double &b, double &c);
    void solveQuadratic(double a, double b, double c, double &x1, double &x2);
    

    例如,函数getCoefficients,变量a,b,c通过引用传递,因此如果三个变量的值在getCoefficients函数中更改,则主函数的值也将在主函数中更改。

    链接地址: http://www.djcxy.com/p/20612.html

    上一篇: 没有按照我的要求执行

    下一篇: C ++通过引用或按值传递?