Variable swapping using function call by reference – CSKC
Sign In

Search

Code Learning #CPP#2685    siteicon   siteicon  

Variable swapping using function call by reference

Swapping (Interchange) of two variable values using the call by reference technique of function arguments.

Learning Objectives

  • Interchange of values using call by reference arguments based functions.
  • Change two input variables, which can not be done by returning values from function.

Source Code

TC++ #2685

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

void swap(int &,int &);
Function prototype with two locations for integer storage passed as reference using addressof (&) operator

int a=10,b=13; cout <<“The original values are : “;cout <<” a = “<<a<<“, b = “<<b<<endl;
Two variables set and displayed the values as set.

swap (a,b);
The function swap is called with actual parameters as a and b where instead of parameter value its locations will be passed to the called function

cout <<“nThe values after swap () are : “; cout <<” a = “<<a<<“, b = “<<b<<endl;
The function called actually interchanges the value and thus interchanged values are printed here.

void swap(int &x,int &y)
This is function definition header with two formal parameters passed as reference and not as value.
{
int temp ; temp = x ; x = y ; y = temp ;
This is the typical swapping logic as can be understood in details at #2493
}

Notes

  • This type of swapping can not be done easily by using call by value and returning as a typical function can return only one value.

Common Errors

  • The swapping sequence should always be maintained for correct swapping otherwise same value may be accidentally put in both variables.


Suggested Filename(s): cbr-swap.cpp



Share

Created: 16-Jan-2018 23:41 | Updated: 16-Jan-2018 23:54|