Passing arguments

For examplatory reasons I will do a very simple type of function and leave it to you to find out how it works exactly.
  • Passing by value (and const value):
    #include <iostream.h>

    void f1(int x) {
        cout<<"The value of x = "<< x << endl;
        x *= 3;
        cout<<"The value of 3x = "<< x << endl;
    }

    int main() {
        f1(44);
        f1(44-21);
        int u = 17;
        f1(u);
        cout << "u = " << u << endl;
        f1(5*u-32);
    }


    Here the sequence of outputs would be something like
    The value of x = 44
    The value of 3x = 132
    The value of x = 23
    The value of 3x = 69
    The value of x = 17
    The value of 3x = 51
    u = 17
    The value of x = 53
    The value of 3x = 159

    In case you do not change the value by any means, you might add a const in front of it. In our example case, this boils down to
    #include <iostream.h>

    void f2(const int x) {
        cout<<"The value of x = "<< x << endl;
    }

    without any noticeable changes. This extra assignment const has the main effect to ease up the compilers work and to keep you (the programmer) honest. Of course, statements like x *= 3 are not allowed within this function.
  • Passing by reference:
    In "passing by values" you insert directly the value into your function, whereas in "passing by reference" you pass the address of your object inside the memory to your function to work with it. The latter version allows to persistently change the value within this address.
    Just one more word to how "passing by value" and "passing by reference" work: In the former, the value is copied into a new address in memory (instantiated) to work with it. When leaving the function this memory is freed again, the value deleted. In the latter, no new instance is created, instead the code works with the already available instance.

    Let me contrast the examples above with:
    #include <iostream.h>

    void f3(int & x) {
        cout<<"The value of x = "<< x << endl;
        x *= 3;
        cout<<"The value of 3x = "<< x << endl;
    }

    int main() {
        int u = 17;
        f3(u);
        cout << "u = " << u << endl;
    }


    In contrast to passing by value, the passing by reference (indicated by the &) allows the function to change the value of the argument. Consequently the output would look like:
    The value of x = 17
    The value of 3x = 51
    u = 51

    Note, that you always have to pass a variable from the main-method to the function to allow the complier to instantiate a reference to it. I would like to stress the similarity with pointers.

    [prev] [top] [next]