In C ++, we can pass arguments to functions via Pointers or references. In both cases, we get the same result. Therefore, the following problems are unavoidable; When is it better than another? What are the reasons why we use one for the other?

Through the pointer:

Output:

A is 45, b is 35

A is equal to 35, b is equal to 45

Pass by reference:

Reference variable and pointer variable

This is usually done using Pointers. A reference is the same object with a different name, and a reference must refer to an object. Since references cannot be NULL, they are safer to use.

1. Pointers can be reassigned when references cannot be reassigned, and only at initialization.

2. Pointers can be directly assigned to NULL, but references cannot.

3. The pointer traverses arrays, and we can use ++ to go to the next item the pointer points to.

4. Pointers are variables that hold memory addresses. A reference has the same memory address as the item it references.

5. Pointers to classes/structures use -> (arrow operator) to access their members, while references use ‘. (dot operator)

6. Pointers need to be dereferenced with * to access the memory location they point to, while references can be used directly.

Output (may vary from run to run because we print the address in the program)

Usage in parameter passing:

Whenever we don’t need to “reset”, a reference is usually preferable to a pointer.

In general, use references whenever possible, and Pointers must be used. However, if we want to write C code that compiles with both C and C ++ compilers, we must limit the use of Pointers.

Every day to learn a little knowledge, I hope to help you ~

In addition, if you want to improve your programming ability, learn C language C++ programming! Pass on the curve, one step faster! The author here may be able to help you ~

Share (source code, project actual combat video, project notes, basic introduction tutorial)

Welcome to change careers and learn programming partners, use more information to learn and grow faster than their own thinking oh!