Explain the concept of pass by reference. How it differs from pass by value

C++ Programming: From Problem Analysis to Program Design
8th Edition
ISBN:9781337102087
Author:D. S. Malik
Publisher:D. S. Malik
Chapter18: Stacks And Queues
Section: Chapter Questions
Problem 9SA
icon
Related questions
Question

Explain the concept of pass by reference. How it differs from pass by value

Expert Solution
Step 1

Pass by reference :It means to pass the reference of an argument in the calling function to the corresponding formal parameter of the calling function.

The called function can modify the value of the argument by using its reference passed in.

 

Example:

            void swapNums(int &x, int &y) {

            int z = x;

            x = y;

            y = z;

         }

 

           int main() {

           int firstNum = 10;

           int secondNum = 20;

 

           cout << "Before swap: " << "\n";

           cout << firstNum << secondNum << "\n";

 

           // Call the function, which will change the values of firstNum and secondNum

         swapNums(firstNum, secondNum);

         cout << "After swap: " << "\n";

        cout << firstNum << secondNum << "\n";

 

       return 0;

     }

Step 2

Pass by reference is differ from pass by value as in pass by value a copy of the actual parameter's value is made in memory.

i.e. the caller and callee have two independent variables with the same value.

If the callee modifies the parameter value, the effect is not visible to the caller. 

Now use of pass by value if we are building multi-threaded application, then we don’t have to worry of objects getting modified by other threads.

 

 

In distributed application pass by value can save the over network overhead to keep the objects in sync.

The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

By default, C programming uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function

steps

Step by step

Solved in 3 steps

Blurred answer
Knowledge Booster
Types of Loop
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program…
C++ Programming: From Problem Analysis to Program…
Computer Science
ISBN:
9781337102087
Author:
D. S. Malik
Publisher:
Cengage Learning
C++ for Engineers and Scientists
C++ for Engineers and Scientists
Computer Science
ISBN:
9781133187844
Author:
Bronson, Gary J.
Publisher:
Course Technology Ptr