C++ Lab6a We\'ve seen two ways we can write a function that swaps the values of
ID: 3920657 • Letter: C
Question
C++ Lab6a
We've seen two ways we can write a function that swaps the values of two int variables: one way passes the ints by reference, the other way passes the addresses of those ints. Write a swap function that uses both - it should pass one int variable by reference, and should pass the address of the other int variable, and the function should then swap those two values. Write a main function that declares and initializes two int variables, calls your swap function, and then prints out the two variables, showing that their values were correctly swapped.
Explanation / Answer
#include <iostream>
using namespace std;
void swap(int &a,int*b)
{
int temp;
temp=a;
a=*b;
*b=temp;
cout<<"a: "<<a<<" b: "<<*b<<endl;
}
int main() {
int a,b;
cout<<"Enter the number to swap"<<endl;
cin>>a>>b;
swap(a,&b);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.