0
votes

I'm a beginner in c++ and I think I understand pointers and references, and started using them as parameters to functions. Is there ever a time for a function parameter to be a pointer, when a reference is less work and is easier to understand. For example, pointer as parameter:

#include <iostream>

using namespace std;

void add_one(int *x);

int main() {
    int a = 0;
    add_one(&a);
    cout << a << "\n";
    add_one(&a);
    cout << a << "\n";
    add_one(&a);
    cout << a << "\n";
}

void add_one(int *x) {
    *x += 1;
}

vs reference as parameter

#include <iostream>

using namespace std;

void add_one(int &x);

int main() {
    int a = 0;
    add_one(a);
    cout << a << "\n";
    add_one(a);
    cout << a << "\n";
    add_one(a);
    cout << a << "\n";
}

void add_one(int &x) {
    x += 1;
}
In c++ we use pass by reference. In c which did not have pass by reference we had to pass by pointer to modify the passed in value.drescherjm
when nullptr is a valid parameter you can use a pointer463035818_is_not_a_number
there are are cases, like if you had an 'optional' parameter, like i dont know a function that can do some extra logging of debug information if you pass a logger but wont if its not present so you would have if (logger) logger->AddMessage("xyz");, arrays whose size you dont know at compile time (see fstream's write), and probably other cases i cant think of right nowBorgleader
One use case in c++ for pass by pointer that was used is an optional bool that is an out parameter. For example: https://doc.qt.io/qt-5/qstring.html#toInt in modern c++ there are other ways this can be accomplished.drescherjm
A lot of pointer use cases in C++ exist because they also existed in C, and we've been lugging that legacy for a while. In general, you should avoid using pointers if alternatives are available.Etienne de Martel