Call by value in cpp

Call by value in cpp is another method to passing value to function in c++.

In this tutorial we will see what is function, C++ function call by value, and call by value program in cpp.

What is function :  function is block of code.

Call by value : When function are called by passing the value they are called as call  by value.

We simple pass value of the variable to function.

And the formal variable creates its own copy of the variable with value passed to it.

Call by value example

call by value example
call by value example

we will see program to swap two numbers using function by call by value.

C++ program to swap two numbers using call by value.

123456789101112131415161718192021222324252627#include <iostream>using namespace std;void swap(int ,int );//Call By Valueint main(){    int a,b;    cout<<“\nEnter Two Number To Swap :\n”;    cin>>a>>b;cout<<“\n Before Numbers :\n\n”; cout<<“x= “<<a<<”   “<<“y= “<<b<<” \n”;    cout<<“\nAfter Swapping Numbers :\n\n”;    swap(a,b);    return 0;}void swap(int x,int y){ int z; z=x; x=y; y=z; cout<<“x= “<<x<<”   “<<“y= “<<y<<” \n”;}

Output :

C++ Program To Swap Two Numbers Using Functions
C++ Program To Swap Two Numbers Using Functions

Explanation :

1. First we declare the function which is swap function

=> void swap(int ,int );

2. Execution starts with the main method.

3. Declare the variables

a, b => to store two numbers

4. Take a input from user two numbers

=>  cin>>a>>b;   a = 10, b= 20

5. We print numbers before swapping.

6. Next we call function by passing value a and b .

swap(a,b);  => function get executed

swap(int x,int y) {   => x= 10 y = 20

z=x;   => z=10

x=y;  => x=20

y=z;  => y = 10

7. Now we print numbers after swapping

cout<<“x= “<<x<<” “<<“y= “<<y<<” \n”;

} => Returns to main function

8. End with the program.