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;
}
c++
we use pass by reference. Inc
which did not have pass by reference we had to pass by pointer to modify the passed in value. – drescherjmnullptr
is a valid parameter you can use a pointer – 463035818_is_not_a_numberif (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 now – Borgleader