Search code examples
c++functionpointersreferenceprototype

Passing Pointers By Reference vs Passing Pointers Into Functions


It's been a while since I've coded anything in C++. While I was trying to help another person as a CIS Tutor, he wanted to know why it's necessary to have an ampersand next to a pointer to an int.

I figured that if you were to pass a pointer by reference and you point to something else, the main knows after you passed that val will equal to whatever you set it equal to.

There will be an example below will demonstrate what I'm trying to say.

Is this correct?

//main function
int variable = 0;
int* val = &variable;
function1(val);
cout << *val << endl;
function2(val);
cout << *val << endl;
//Passing in a pointer with reference.
void function1(int*& value)
{
    int variable = 9;
    value = &variable;
}

//Passing in a pointer without reference.
void function2(int* val)
{
    int variable = 9;
    value = &variable;
}

My assumption is that the program will output 9 instead of 8 or 0. I hope this give you guys a clear picture of what I'm trying to ask.


Solution

  • The difference between passing the values and passing the reference is the same with pointers as with other values (actually pointers are nothing special they just hold numbers that sometimes are adresses of other objects).

    With int:

    void foo(int x) { x = 1; }
    void bar(int& x) { x = 2; }
    
    int main() {
        int y = 5;
        foo(y);
        std::cout << y; // prints 5
        bar(y); 
        std::cout << y; // prints 2
    }
    

    Now with pointers:

    void foo(int* x) { x = 0; }
    void bar(int*& x) { x = 0; }
    
    int main() {
         int y = 42;
         int* z = &y;
         foo(z);     
         std::cout << z; // prints the address of y
         bar(z); 
         std::cout << z; // prints 0
    }
    

    Note that your function1 is broken, because when you call it

    int* y;
    function1(y);
    std::cout << *y;    // **baaam**
                        // the value y points to is already gone
    

    the int inside the function ends its lifetime when the function returns and the caller cannot use the value in any meaningful way. Note that in this particular example you would probably get the "correct" value printed, but that is just by coincidence and dereferencing y after passing it to function1 is undefined behaviour.