[ create a new paste ] login | about

Link: http://codepad.org/3OD0sVvw    [ raw code | output | fork ]

johannes - C++, pasted on Nov 2:
#include <iostream>
#include <assert.h>

static int five = 5;
static int nine = 9;

void takeInt(int x)
{
    x = 0;
}

void takeIntRef(int &r)
{
    r = 0;
}

void takePtr(int *p)
{
    *p = 1;
    p = &five;
}

void takePtrToPtr(int **p)
{
    **p = 789;
    *p = &five;
}

void takeRefToPtr(int *&rp)
{
    *rp = 1;
    rp = &nine;   
}

int main()
{
    int n = 123;
    takeInt(n);                       // local copy is modified
    std::cout << n << std::endl;      // 123 (value unchanged)

    takeIntRef(n);                    // value passed by reference, original is modified
    std::cout << n << std::endl;      // 0 (assigned in function)

    int *pt = &n;                     // pt points to n
    takePtr(pt);                      // pointer is passed by value

    assert(pt == &n);                 // pointer has not changed (p still points to n) ...
    std::cout << n << std::endl;      // 1 ... but pointee has

    takePtrToPtr(&pt);                // pass a pointer to pt (= pointer to a pointer to n)
    assert(pt != &n);                 // this time the pointer has changed,
                                      // pt now no longer points to n

    std::cout << *pt << std::endl;    // 5
    assert(pt == &five);              // indeed, pt points to the static "five"

    std::cout << n << std::endl;      // 789 (changed in first line of takePtrToPtr) 

    takeRefToPtr(pt);                 // pass a pointer by reference
    std::cout << *pt << std::endl;    // 9 (pt is now modified in function)

    return 0;
}


Output:
1
2
3
4
5
6
123
0
1
5
789
9


Create a new paste based on this one


Comments: