0

I am supposed to write a function name double_swap that takes two doubles as arguments and interchanges the values that are stored in those arguments. The function should return no value, so I know that means it must be a void function.

For example, if the following code fragment is executed,

int main() { double x = 4.8, y = 0.7; double_swap(x,y); cout<<"x = "<<x<<" y = "<<y; } 

The output will be: x = 0.7 y = 4.8

The program I wrote is not swapping the values. I'd greatly appreciate if someone could point out my errors.

#include <iostream> using namespace std; void double_swap(double x, double y) { x = 1.9; y = 4.2; } int main() { double x = 4.2, y = 1.9; double_swap(x,y); cout<<"x = "<<x<<" y = "<<y<<endl; return 0; } 
0

2 Answers 2

5

You need to pass the variables by reference in order for the modifications in the function to apply to the variables from the call site. As it is right now all you are doing is modifying copies that get destroyed once the function ends.

Change

void double_swap(double x, double y) 

to

void double_swap(double& x, double& y) 

Also instead of hard coding the values lets do a real swap using

void double_swap(double& x, double& y) { double temp = x; x = y; y = temp; } 

You could also use pointers for the function paramters for this but then your call site would have to be changed to double_swap(&x,&y); and you would have to remember to reference the pointers in the function.

Instead of doing all of this though we can just use std::swap and let it do this for us.

Sign up to request clarification or add additional context in comments.

1 Comment

there is also a problem with the body
0

When calling a function in c++ , There is 3 way to pass the parameters. The first one is by Copy where it only make a copy of the variable in parameters and then delete them.

 void double_swap(double x, double y) 

The second one is by Reference, where the paramaters refere to the real variable (Whats you want).

 void double_swap(double& x, double& y) 

And the last one is by address where you pass the address of the variables.

 void double_swap(double* x, double* y) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.