'When to use pointer as parameter in function c++?
I'm a beginner in C++. 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, using a 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;
}
versus a 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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
