Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write three functions swap_v(int,int), swap_ r(int&,int&), and swap cr(const int

ID: 3755503 • Letter: W

Question

Write three functions swap_v(int,int), swap_ r(int&,int&), and swap cr(const int&, const int&). Each should have the body int temp; temp a, a-b; b-temp; ) where a and b are the names of the arguments Try calling each swap like this int x -7 int y-9; swap_?(x,y); swap_?(7,9); const int cx-7; const int cy 9 swap_?(cx,cy); swap-7(7.7,9.9); double dx -7.7; double dy-9.9; swap_?(dx,dy); swap ?(7.7,9.9); I replace ? by v,r,or cr Which functions and calls compiled, and why? After each swap that com piled, print the value of the arguments after the call to see if they were actually swapped. If you are surprised by a result, consult 88.6

Explanation / Answer

swap_v( int x , int y )

will compile but will not swap the original values of the values of x and y. It is because the values are passed by value. So, any change to the arguments in the function will not change the original variables.

swap_r( int& x , int& y )

will compile and swap the values of x and y as the values are passed by reference. So, any change to them in the function will also change the original values.

swap_cr( const int& x, const& int y )

will cause error . It is because the values are const. So, they can't be changed. So, it will cause error.

So, this function used any time in the program will cause error.

Now,

x = 7

y = 9

Now,

swap_v( x , y )

After this,

x = 7

y = 9

as values are passed by value.

Also

swap_r( x , y )

After this,

x = 9

y = 7

as values are passed by reference.

swap_cr(x , y)

will cause error as x and y are not const.

Now,

swap_?( 7 , 9 )

it will compile and run for swap_v() and swap_r() , but will cause error for swap_cr().

But it will not affect anything as only the numbers are passed.

swap_?( cx , cy )

will cause error for all the three methods. It is because the variable cx and cy are read only. So, it will cause error.

Now,

swap_?( 7.7 , 9.9 )

it will compile and run for swap_v() and swap_r() , but will cause error for swap_cr().

But it will not affect anything as only the numbers are passed.

Now,

swap_v( dx , dy )

After this,

dx = 7.7

dy = 9.9

as values are passed by value.

Also

swap_r( x , y )

After this,

x = 9

y = 7

as values are passed by reference.  Also the values are rounded to int as argument of type int.

swap_cr(x , y)

will cause error as x and y are not const.

Now,

swap_?( 7.7 , 9.9 )

it will compile and run for swap_v() and swap_r() , but will cause error for swap_cr().

But it will not affect anything as only the numbers are passed.