The symbolic name for “data” that passes into a function.
    传递给函数的“数据”的符号名称。

    函数的参数是变量名,用来把数据从调用函数的环境传递到被调用的环境中去,参数传递的过程叫做传参。
    传参的两种方式Two ways to pass into a function:

    • Pass by value
    • Pass by reference

    Pass by value: fundamental type(基本数据类型)
    The parameter is a copy of the original variable

    1. int foo(int x)
    2. { // x is a copy
    3. x += 10;
    4. return x;
    5. }
    6. int main()
    7. {
    8. int num1 = 20;
    9. int num2 = foo( num1 );
    10. return 0;
    11. }

    基本数据类型作为函数参数的时候,传递的是数据的拷贝。num1 是作为参数传递给函数foo,函数中的x是一个局部变量,是num1的拷贝,局部变量x的值在foo()内部执行加10操作,但是num1的值不会改变。函数中return的值也是一个拷贝,将拷贝的值赋值给num2

    Pass by value: pointer
    What’s the difference?和上面代码会有什么差异呢?

    1. int foo(int * p)
    2. {
    3. (*p) += 10;
    4. return *p;
    5. }
    6. int main()
    7. {
    8. int num1 = 20;
    9. int * p = &num1;
    10. int num2 = foo( p );
    11. return 0;
    12. }

    It still is passing by value (the address!)
    A copy of the address

    传递给函数的是num1所在的地址,然后将拷贝之后的地址传递给函数,在函数中,该地址的值执行加10操作,就是执行了num1中的内容。

    1. #include <iostream>
    2. using namespace std;
    3. int foo1(int x)
    4. {
    5. x += 10;
    6. return x;
    7. }
    8. int foo2(int *p)
    9. {
    10. (*p) += 10;
    11. return *p;
    12. }
    13. int main()
    14. {
    15. int num1 = 20;
    16. int num2 = foo1(num1);
    17. cout << "num1=" << num1 << endl;
    18. cout << "num2=" << num2 << endl;
    19. int *p = &num1;
    20. int num3 = foo2(p);
    21. cout << "num1=" << num1 << endl;
    22. cout << "*p=" << *p << endl;
    23. cout << "num3=" << num3 << endl;
    24. return 0;
    25. }
    26. // num1=20
    27. // num2=30
    28. // num1=30
    29. // *p=30
    30. // num3=30

    Pass by value: structure
    How about structure parameter?

    1. struct Matrix
    2. {
    3. int rows;
    4. int cols;
    5. float * pData;
    6. };
    7. // 找矩阵中的最大值
    8. float matrix_max(struct Matrix mat)
    9. {
    10. float max = FLT_MIN;
    11. for(int r = 0; r < mat.rows; r++)
    12. for (int c = 0; c < mat.cols; c++)
    13. {
    14. float val = mat.pData[ r * mat.cols + c];
    15. max = ( max > val ? max : val);
    16. }
    17. return max;
    18. }
    // 实例化一个Matrix,行列为3,4,
    Matrix matA = {3,4};
    matrix_max(matA);
    

    mat也是一个变量,当被调用时,其也会被拷贝一份,传入函数进行调用,同之前两种情况相同。如果通过pData的地址修改了内容,matA的成员变量虽然没有被修改,但是pData指向的数据被修改了。

    Now, pass by value.
    But if the structure is a huge one, such as 1K bytes.每一次的参数调用都要拷贝一份,这个内存消耗就很大了。
    A copy will cost 1KB memory, and time consuming to copy it.

    那就是引用!!!