+92 332 4229 857 99ProjectIdeas@Gmail.com

How to swap two variables-Passing ByValue and ByReference (C++)


How to swap 2 numbers

Swap() function has 2 overloads in this program:

First overload takes two integers as an input parameter and

Second overload takes the reference of two integers as an input parameter.

First function doesnot returns the result of the swapped variables because a function cannot return more than 1 variable at a time so we have used type of the function to be void. So it is not flexible to pass variables by value.

Second function is more flexible because it takes variables as reference and swaps two variables because this overload deals with pointer (the actual value of the variable in the memory) not with the value of the variable.


Code

#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

void swap( int num1 , int num2)
{
int temp = num1;
num1 = num2;
num2 = temp;
}

void swap( int*num1 , int*num2)
{
int temp = *num1;
*num1 = *num2;
*num2 = temp;
}

int main()
{
int num1;
int num2;

num1 = 5;
num2 = 6;

       cout << "Before swapping  > " << num1 << " " << num2 << endl;
       swap( num1 , num2 );
       cout << "After swapping   > " << num1 << " " << num2 << " swap() first  overload" << endl;
       swap( &num1 , &num2 );
       cout << "After swapping   > " << num1 << " " << num2 << " swap() second overload" << endl;

       _getche();
       return 0;
}

Output
Before swapping  > 5 6
After swapping   > 5 6 swap() first  overload
After swapping   > 6 5 swap() second overload

0 comments: