Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pass by Reference and Pass by Value

Status
Not open for further replies.

Lonerd

Programmer
Dec 7, 2021
1
IN
I am a bit confused, can anyone please explain when exactly one should use pass by reference and pass by value in CPP functions?
 
When you pass by reference three things happen:

1. You are guaranteed that the parameter is not NULL.
2. It gives you a simplified syntax for accessing what is essentially a pointer under the hood.
3. The original value can be updated and passed around, allowing a called function to update the source value.

When you pass by value, you're creating a copy and any changes made will only operate upon the copy.

Whether or not you pass by reference is determined by whether or not you need to update the source value. And possibly also if the value is a large block of data, passing by reference only consumes 4 bytes of stack space for 32-bit, or 8 bytes for 64-bit, and is more conducive to performance.

--
Rick C. Hodgin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top