When do you use reference and pointer, respectively?

Asked 2 years ago, Updated 2 years ago, 50 views

I know how to write reference and pointer. What I want to know is Which is more appropriate to write reference or pointer.

In some cases, this is specified (for example, the ++ operator only writes reference) and is not specified Usually, when a variable changes in the middle, everyone uses a pointer.

void add_one(int& n) { n += 1; }
void add_one(int* const n) { *n += 1; }
int main() {
  int a = 0;
  I don't know if add_one(a); // a changes or not. a = a+1 may be returned, but a+1 may be returned?
  expected to change add_one(&a); // a
}

Rather than using a reference, you can see what you're doing right now Is it better to use a pointer than a reference to convey clearly what you're doing? Then should I use the reference only when I really need it (++ operator)?

c++ reference pointer

2022-09-21 16:10

1 Answers

It is best not to use a pointer.

Using a pointer makes it difficult to read or follow the code. This code is not secure. Unexpected situations can happen later.

So the best way is to use a pointer only when you think there's no other way. For example, if the function can return nullptr, you must return the pointer.

In the code you asked, you do not need to write pointer for the following reasons. Receiving pointer as a factor value is accepted as receiving nullptr as a factor, and nullptr also means that the function works well.

However, in the code you asked,

Therefore, we recommend that you write reference.


2022-09-21 16:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.