5.4. Parameter Passing by Value

[ fromfile: functions.xml id: valueparm ]

Example 5.11. src/functions/summit.cpp

#include <iostream>

int sumit(int num) {
    int sum = 0;
    for (; num ; --num)  1
        sum += num;
    return sum;
}


int main() {
    using namespace std;
    int n = 10;
    cout << n  << endl;
    cout << sumit(n) << endl;
    cout << n << endl;  2
    return 0;
}
Output:

  10
  55
  10



1

The parameter gets reduced to 0.

2

See what sumit() did to n.


Example 5.12. src/functions/pointerparam.cpp

#include <iostream>
using namespace std;

void messAround(int* ptr) {
    *ptr = 34;       1
    ptr = 0;         2
}


int main() {
    int n(12);       3
    int* pn(&n);     4
    cout << "n = " << n << "\tpn = " << pn << endl;
    messAround(pn);  5
    cout << "n = " << n << "\tpn = " << pn << endl;
    return 0;
}
Output:

n = 12  pn = 0xbffff524
n = 34  pn = 0xbffff524


1

Change the value that is pointed to.

2

Change the address stored by ptr. Better not dereference this!

3

Initialize an int.

4

Initialize a pointer that points to n.

5

See what is changed by messAround().


[Note]Note

To summarize:

  • When an object is passed by value to a function, a copy is made of that object.

  • The copy is treated as a local variable by the function.

  • The copy is destroyed when the function returns.