C Language Interview – Usage Scenarios of Pointers and References

C Language Interview - Usage Scenarios of Pointers and References

First, let’s address two questions

◆ What are the differences between pointers and references?

◆ When should we use pointers? When should we use references?

Differences between Pointers and References

See the code below:

C Language Interview - Usage Scenarios of Pointers and References

A pointer is used to represent a memory address, and this pointer is an integer that is the address of the variable it points to.

A reference, on the other hand, is simply another name for a variable; a reference is an “alias”.

Differences

◆ A pointer can be declared without initialization, but it must be checked each time it is used to prevent null pointer exceptions. A reference can never be null; it must always refer to an object.

C Language Interview - Usage Scenarios of Pointers and References

◆ A pointer stores an address and can be reassigned. A reference always points to the object it initially represents.

Usage Scenarios for Pointers and References

References are mainly used as function parameters and return values, as shown in the code below:

C Language Interview - Usage Scenarios of Pointers and References

By using vec[3] = 3, we can change the value of the vector container. This is because the [] operator returns a reference. It gives an alias to the internal variable and allows the [] operator to return a pointer, i.e., *vec[3] = 3. In fact, whatever a reference can do, a pointer can also do. So why use references?

Conclusion

Use the right tool for the right job.

Pointers can operate on anything in memory without constraints, making them very powerful but also dangerous. Therefore, references should be used at appropriate times. When you need to point to something and ensure it never points to anything else, such as in some function parameters to avoid copying, you can use references. Alternatively, when implementing an operator that cannot be achieved with pointers due to syntax requirements, such as vec[3] = 3, you can use references. In all other cases, pointers should be used.

Leave a Comment